Nothing Special   »   [go: up one dir, main page]

Embedded System Material

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 143

EMBEDDED SYSTEM DESIGN 1

EMBEDDED SYSTEMS
EMBEDDED SYSTEM DESIGN 2

INDEX
CONTENT PAGE NO.
UNIT 1: INTRODUCTION TO EMBEDDED SYSTEMS 4-11

1. HISTORY
2. EXAMPLES
3. HARDWARE
4. SOFTWARE
5. SAFETY AND RELIABILITY
6. DIFFERENCE BETWEEN MICROPROCESSOR AND MICROCONTROLLER

UNIT 2: 8051 ARCHITECTURE 12-25

1. ARCHITECTURE OVERVIEW
2. PIN CONFIGURATION
3. INPUT/OUTPUT PINS
4. MEMORY
5. ADDRESSING MODES

UNIT 3: COUNTERS AND TIMERS 26-32

UNIT 4: SERIAL COMMUNICATION 33-39

UNIT 5: 8051 INTERRUPTS 40-43

INSTRUCTIONS FOR 8051 AND REVIEW QUESTIONS 44-45

UNIT 6: INTRODUCTION TO PIC 46-48

UNIT 7: PIC18F452 DEVICE OVERVIEW 49-56

UNIT 8: INPUT/OUTPUT PORTS 56-59

UNIT 9: TIMERS IN PIC18F452 60-68

UNIT 10:ADDRESSABLE USART 69-74

UNIT 11: INTERRUPTS IN PIC18F452 75-88

INSTRUCTIONS AND REVIEW QUESTIONS FOR PIC18F452 89-90

UNIT 12: INTRODUCTION TO ARM 91-102

UNIT 13: TIMERS IN ARM 102-103

UNIT 14: SERIAL COMMUNICATION IN ARM 104-109

UNIT 15: INTERRUPTS IN ARM 110-112

UNIT 16: BASICS OF EMBEDDED C PROGRAMMING 113-117

INTERFACING 118

SOFTWARE STEPS FOR PROTEUS 131

SOFTWARE STEPS FOR FLASH MAGIC 137


EMBEDDED SYSTEM DESIGN 3

UNIT-1: INTRODUCTION
An Embedded system is a computer that has been built to solve only a few very specific problems and is not
easily changed. In contrast, a general-purpose computer can do many different jobs, and can be changed at any time
with new programs for new jobs. An embedded system usually does not look like a computer, often there is no
keyboard or monitor or mouse. But like any computer it has a processor and software, input and output.
For example, a controller is embedded in an elevator and tells the motor to move the elevator to different
floors based on buttons that are pushed. A decoder is embedded in a satellite television set-top box to read a signal
from the dish and send something that a TV understands. Often this type of system must do its work in a specific
amount of time. This is called real-time computing. A general purpose computer will quite often have short pauses
while it does something else, it is not real-time.
Some embedded systems use specially-built small and simple operating systems that start very quickly, others
do not need one at all.
In contrast to this, a general-purpose computer needs to be ready for new device drivers and software to run
hardware it doesn't know about yet, like new printers or hard drives. Embedded systems control many of the common
devices in use today, from card readers in hotel door locks to many controls in a car. They can be small like an MP3
player or a digital camera, to large systems like traffic lights, airplane controls, or assembly line controllers in a
factory.
Modern embedded systems are often based on microcontrollers (i.e. CPUs with integrated memory and/or
peripheral interfaces) but ordinary microprocessors (using external chips for memory and peripheral interface circuits)
are also still common, especially in more complex systems.
Physically, embedded systems range from portable devices such as digital watches and MP3 players, to large
stationary installations like traffic lights, factory controllers, and largely complex systems like hybrid vehicles, MRI,
and avionics. Complexity varies from low, with a single microcontroller chip, to very high with multiple
units, peripherals and networks mounted inside a large chassis or enclosure.

1. HISTORY
One of the very first recognizably modern embedded systems was the Apollo Guidance Computer, developed
by Charles Stark Draper at the MIT Instrumentation Laboratory. At the project's inception, the Apollo guidance
computer was considered the riskiest item in the Apollo project as it employed the then newly developed monolithic
integrated circuits to reduce the size and weight.
An early mass-produced embedded system was the Automatics D-17 guidance computer for the Minuteman
missile, released in 1961. When the Minuteman II went into production in 1966, the D-17 was replaced with a new
computer that was the first high-volume use of integrated circuits. The first microprocessor for example, the Intel
4004, was designed for calculators and other small systems but still required external memory and support chips.
In 1978 National Engineering Manufacturers Association released a "standard" for programmable
microcontrollers, including almost any computer-based controllers, such as single board computers, numerical, and
event-based controllers. Microcontrollers find applications where a general-purpose computer would be too costly.A
comparatively low-cost microcontroller may be programmed to fulfill the same role as a large number of separate
EMBEDDED SYSTEM DESIGN 4

components. Although in this context an embedded system is usually more complex than a traditional solution, most
of the complexity is contained within the microcontroller itself. Software prototype and test can be quicker compared
with the design and construction of a new circuit not using an embedded processor

2. EXAMPLES OF EMBEDDED SYSTEMS


Embedded systems are used everywhere in modern life and there are many examples of their use, including:
 Telecommunication systems use them for telephones, cell phone network, and Wi-Fi routers.
 Consumer electronics include clock radios, MP3 players, mobile phones, video game consoles, digital
cameras, DVD players, GPS receivers, home security systems, and printers.
 Transportation uses embedded systems for everything from locomotives for trains, airplanes and
automobiles.
 Industry uses electric motors with electronic motor controllers, card readers and CNC machines which
automatically make metal parts.
 Medical devices like defibrillators, automated blood pressure readers, and automated insulin pumps.
 Military device, like walkie-talkies, satellites and the guiding systems for missiles.
 Household appliances like washing machines and dishwashers and microwave ovens have embedded
systems.

3. COMMON FEATURES OF AN EMBEDDED SYSTEM


 Embedded systems are designed to do a specific task, unlike general-purpose computers.
 Many embedded systems must be able to do things in real-time - in a short amount of time (almost instantly
from a human view).
 Many embedded systems must be very safe and reliable, especially for medical devices or avionics controlling
airplanes.
 Starts very quickly. People don't want to wait a minute or two for their car to start or emergency equipment to
start.
 It uses a special operating system (or sometimes a very small home-made OS) that helps meet these
requirements called a real-time operating system, or RTOS.
 The program instructions written for embedded systems are referred to as firmware, and are stored in read-
only memory or flash memory chips.
 They run with limited computer hardware resources: little memory, small or non-existent keyboard and/or
screen.

4. USER INTERFACES:

1) An example of a user interface with buttons and a simple LCD display 2) Robot


EMBEDDED SYSTEM DESIGN 5

5. HARDWARE
Hardware includes the chips, wires, circuit boards, buttons and displays.

4.1 CPU (CENTRAL PROCESSING UNIT):


The most important chip is the central processing unit or CPU. This runs the software instructions. It can be a
standard microprocessor or a microcontroller. Microcontrollers include the microprocessor as well as
simple peripheral equipment so the system can be smaller and cheaper. They have less flexibility because those parts
cannot be changed. Usually these parts include Flash memory and support for serial ports, USB, etc.
Unlike a microprocessor for a general-purpose computer, bigger and faster is not always better. Many
embedded processors are very small. Sometimes this is to use less space or less power; sometimes it is to be cheaper.
General-purpose computers will use microprocessors that read 32-bit or 64-bit words and run at speeds measured in
GHz, but embedded processors are usually 4 to 32 bits and run at speeds usually measured in tens of MHz (a hundred
times slower). (But the programs are also smaller and do not check for things that are not used).

4.2 READYMADE COMPUTER BOARDS:

An embedded system targeted at network applications. There are "ready-made" computer boards that can be
used in some embedded systems. These often use Windows CE, Linux, Net BSD, or an embedded real-time operating
system.
Sometimes it may be easier to use a circuit board that is already made. These usually share
many components with general purpose computers, but are smaller than one in a general purpose computer. The
advantage is that it saves some electrical engineering time and can use the same software development tools used for
PC-type software development. Examples of such embedded devices are the ATMs or displays in casinos. This works
well if the real-time requirements are not real strict.

4.3 ASIC AND FPGA SOLUTIONS:


If the device needs to be very small or will be sold in very big numbers it makes sense to make a custom or
specialized chip that does exactly what is needed. This is a system on a chip (SoC) which holds a complete system
processor, floating point unit, memory cache and interfaces on a single integrated circuit.
SOCs can be made as a special-order application-specific integrated circuit (ASIC) or by using a field-
programmable gate array (FPGA) which is programmed by the people building the embedded system.
EMBEDDED SYSTEM DESIGN 6

4.4 PERIPHERALS:
Embedded systems talk with the outside world or other components using peripherals such as:
 Serial Ports: RS-232, RS-422, RS-485. This used to be quite common, with the 9-pin (or larger) connectors.
 Synchronous Serial Communication Interface: I²C Inter-Integrated Circuit, I²S Inter-Integrated
Sound, SPI, Micro wire, ...
 Universal Serial Bus (USB).
 Networks: Ethernet, Controller Area Network, Lon Works,
 Discrete Input /Output: General Purpose Input/output (GPIO). This can be a single wire with an on/off signal.
 Analogue to Digital/Digital to Analogue converters (ADC/DAC): This measures something that changes in
strength, like a light sensor or a motor control.
 Debugging: JTAG, ICSP port, for software engineers.

6. SOFTWARE

5.1 OPERATING SYSTEMS


As embedded systems get bigger, things that used to be only on general-purpose computers or
even mainframes are now becoming common on embedded systems. This includes protected memory space,
and open programming environment .Some examples of operating systems, from simple to complex:
 Simple control loop - A timer and a loop is used to call different subroutines repeatedly. This is often made by one
person for smaller systems.
 Interrupt controlled - The tasks are started by different kinds of events. The event could be something timed
(every ten seconds, for example) or by a button press or data received.
 Non-preemptive multitasking - Each task gets its turn to run, and when it finishes it calls a scheduler in the OS to
run the next task.
 Pre-emptive Multitasking Or Multi-Threading - A task can be stopped after some amount of time to let another
task run for a while. No task can hog the system.

Real-time operating systems include products like MicroC/OS-II, Green Hills INTEGRITY,  QNX  or  VxWorks.
Unlike MacOS or Windows 7, these operating systems are not known very well by most people. But they are used in
many places where time and safety is very important. People use them every day and do not realize it.
Common examples of larger kernels are Embedded Linux and Windows CE. Although these do not have the tight
time limits needed for a strict real-time system, they are becoming more common, especially for more powerful
devices such as Wireless Routers and GPSs.

5.2 TOOLS:
Like other software, embedded system designers use compilers, assemblers, and debuggers to develop embedded
system software. However, they may also use some more specific tools:
 For systems using digital signal processing, developers may use a math tools such as MATLAB, Mathcad, or
Mathematic.
 Custom compilers and linkers may be used to improve optimization for the particular hardware.
 An embedded system may have its own special language or design tool, or add enhancements to an existing
language like the one used by Basic Stamp.
EMBEDDED SYSTEM DESIGN 7

5.3 DEBUGGING TOOLS:
 An In-Circuit Debugger (ICD), a hardware device that connects to the microprocessor via a JTAG interface. This
starts and stops the microprocessor from outside as it runs the software. It also allows memory and registers
to be read, and to store the software program in memory.
 External debugging using logging or serial port output to trace operation using either a flashing monitor
 Interactive resident debugging - if the OS supports it, this is a shell on the embedded processor that runs
commands typed by the developer (Linux, for example).
 An in-circuit emulator replaces the microprocessor on the board, providing full control over everything the
microprocessor could do.
 A complete emulator simulates all the features of the hardware, allowing all of it to be controlled and
modified. The hardware doesn't really exist; a pretend version of it (a “virtual" machine) is on a normal PC.
 Checking external lines with a logic analyzer or multimeter.
Unless restricted to external debugging, the programmer can typically load and run software through the tools,
view the code running in the processor, and start or stop its operation.

7. SAFETY AND RELIABILITY


Embedded systems are often in machines that are expected to run for years without errors and in some cases
recover by them if an error occurs. This means the software is usually developed and tested more carefully than that
for personal computers, and unreliable mechanical moving parts such as disk drives and fans are avoided.
Places where safety and reliability are important:
 Some systems cannot safely be shut down for repair, or it is too difficult to repair. Examples include space
systems (satellites, rovers), under-sea cables, and nuclear power plant controls.
 The system could kill people if it fails, such as aircraft controls, chemical factory controls, train signals, and
heart defibrillators.
 The system will lose large amounts of money if it is shut down or if a mistake is made: Telephone switches,
factory controls, cash registers, automated teller machines.

Ways to recover from errors — both software bugs such as memory leaks, and also soft errors in the hardware:

 Watchdog timer that restarts the embedded system if something stops working.


 Duplicate parts, where one system can take over if another one stops working.
 Immunity Aware Programming.
These days designers have many choices in microprocessors/microcontrollers. Especially, in 8 bit and 32 bit, the
available variety really may overwhelm even an experienced designer. Selecting a right microprocessor may turn out
as a most difficult first step and it is getting complicated as new devices continue to pop-up very often.

8. DIFFERENCE BETWEEN MICROPROCESSOR AND MICROCONTROLLER


The term microprocessor and microcontroller have always been confused with each other. Both of them have
been designed for real time application. They share many common features and at the same time they have significant
differences. Both the IC’s i.e., the microprocessor and microcontroller cannot be distinguished by looking at them. 
They are available in different version starting from 6 pin to as high as 80 to 100 pins or even higher depending on the
features.
EMBEDDED SYSTEM DESIGN 8

MICROPROCESSOR:
 Microprocessor is an IC which has only the CPU inside them i.e. only the processing powers such as Intel’s Pentium
1,2,3,4, core 2 duo, i3, i5 etc.
 These microprocessors don’t have RAM, ROM, and other peripheral on the chip.
 A system designer has to add them externally to make them functional.
 Application of microprocessor includes Desktop PC’s, Laptops, notepads etc. 

MICROCONTROLLER:
 Microcontroller has a CPU, in addition with a fixed
amount of RAM, ROM and other peripherals all
embedded on a single chip.
 At times it is also termed as a mini computer or a
computer on a single chip.
 Today different manufacturers produce
microcontrollers with a wide range of features
available in different versions.
 Some manufacturers are ATMEL, Microchip, TI, Free
scale, Philips, Motorola etc. 

Microcontrollers are designed to perform specific


tasks. Specific means applications where the relationship of
input and output is defined. For example, keyboards, mouse, washing machine, digital cam, pen drive, remote,
microwave, cars, bikes, telephone, mobiles, watches, etc. Since the applications are very specific, they need small
resources like RAM, ROM, I/O ports etc and hence can be embedded on a single chip. This in turn reduces the size and
the cost.
Microprocessor find applications where tasks are unspecific like developing software, games, websites, photo
editing, creating documents etc. In such cases the relationship between input and output is not defined. They need
high amount of resources like RAM, ROM, I/O ports etc. The clock speed of the Microprocessor is quite high as
compared to the microcontroller
. Whereas the microcontrollers operate from a few MHz to 30 to 50 MHz, today’s microprocessor operate
above 1GHz as they perform complex tasks.
Comparing microcontroller and microprocessor in terms of cost is not justified. Undoubtedly a microcontroller
is far cheaper than a microprocessor. However microcontroller cannot be used in place of microprocessor and using a
microprocessor is not advised in place of a microcontroller as it makes the application quitecostly.
EMBEDDED SYSTEM DESIGN 9

7.1 MICROCONTROLLER V/S MICROPROCESSOR 


Microprocessors are used to execute big and generic applications, while a microcontroller will only be used to
execute a single task within one application. Some of the benefits of microcontrollers include the following: 

 Cost advantage: The biggest advantage of microcontrollers against larger microprocessors is that the design and
hardware costs are much lesser and can be kept to a minimum. A microcontroller is cheap to replace, while
microprocessors are ten times more expensive.
 
Lesser power usage: Microcontrollers are generally built using a technology known as Complementary Metal Oxide
Semiconductor (CMOS). This technology is a competent fabrication system that uses less power and is more immune
to power spikes than other techniques.
 
All-in-one: A microcontroller usually comprises of a CPU, ROM, RAM and I/O ports, built within it to execute a single
and dedicated task. On the other hand, a microprocessor generally does not have a RAM, ROM or IO pins and
generally uses its pins as a bus to interface to peripherals such as RAM, ROM, serial ports, digital and analog IO.

7.2 HOW DOES A MICROCONTROLLER WORK? 


Microcontroller has an input device in order to get the input and an output device (such as LED or LCD Display)
to exhibit the final process. The Television has a remote control as an Input device and the TV screen as the output
device. The signal sent from the remote control is captured by the microcontroller. The microcontroller controls the
channel selection, the amplifier system and picture tube adjustments such as hue, brightness, contrast etc.

8.3 GENERAL ARCHITECTURE OF A MICROCONTROLLER 

The architecture of a microcontroller depends on the application it is built for. For example, some designs include
us of more than one RAM, ROM and I/O functionality integrated into the package. The architecture of a typical
microcontroller is complex and may include the following:
1) A CPU, ranging from simple 4-bit to complex 64-bit processers.
2) Peripherals such as timers, event counters and watchdog.
3) RAM (volatile memory) for data storage.
4) ROM, EPROM, EEPROM or flash memory for program storage.
5) Serial input/output such as serial ports.
6) A clock generator for resonator, quartz timing crystal or RC circuit.
7) Analog-to-digital convertors.
8) Data bus to carry information
EMBEDDED SYSTEM DESIGN 10

8.4 MICROCONTROLLERS FOR EMBEDDED SYSTEM


A printer is an example of embedded system since the processor inside it performs one task only; namely
getting the data and printing it.
Contrast this with a Pentium based PC. A PC can be used for any number of applications such as word
processor, print-server, bank teller terminal, Video game, network server, or Internet terminal.
In an Embedded system, there is only one application software that is typically burned into ROM. For example,
inside every mouse there is a Microcontroller to perform the task of finding the mouse position and sending it to the
PC.
Table beside lists some embedded
product
EMBEDDED SYSTEM DESIGN 11

8051
MICROCONTROLLER
EMBEDDED SYSTEM DESIGN 12

UNIT-2: 8051 ARCHITECTURE OVERVIEW

2.1 8051 MICROCONTROLLER ARCHITECTURE

Microcontroller producers have been struggling for a long time for attracting more and more choosy
customers. Every couple of days a new chip with a higher operating frequency, more memory and more high-quality
A/D converters comes on the market. Nevertheless, by analysing their structure it is concluded that most of them have
the same architecture known in the product catalogues as “8051 compatible”. What is all this about?
The whole story began in the far 80s when Intel launched its series of the microcontrollers labelled with MCS
051. Although, several circuits belonging to this series had quite modest features in comparison to the new ones, they
took over the world very fast and became a standard for what nowadays is meant by a word microcontroller. The
reason for success and such a big popularity is a skilfully chosen configuration which satisfies needs of a great number
of the users allowing at the same time stable expanding.
Besides, since a great deal of software has been developed in the meantime, it simply was not profitable to
change anything in the microcontroller’s basic core. That is the reason for having a great number of various
microcontrollers which actually are solely upgraded versions of the 8051 family.

As shown on the previous picture, the 8051 microcontroller has:


 4 Kb program memory.
 128Kb RAM (including SFRs).
 4 ports having in total of 32 input/output lines.

The whole configuration is obviously envisaged as such to satisfy the needs of most programmers who work on
development of automation devices. One of advantages of this microcontroller is that nothing is missing and nothing is
too much. In other words, it is created exactly in accordance to the average user‘s taste and needs. The other
advantage is the way RAM is organized, the way Central Processor Unit (CPU) operates and ports which maximally use
all recourses and enable further upgrading.
EMBEDDED SYSTEM DESIGN 13

2.2 8051 PIN CONFIGURATION

PIN 1-PIN 8 (PORT 1): Each of these pins can be configured as input or output.
PIN 9 (RST): Logical ’1’ on this pin stops the microcontroller’s operation and erases the contents of most registers. By
applying logical zero to this pin, the program starts execution from the beginning. In other words, a positive voltage
pulse on this pin resets the microcontroller.
PIN 10- PIN 17 (PORT 3): Similar to port, each of these pins can serve as universal input or output. Besides, all of them
have alternative functions:
PIN 10 (RXD): Serial asynchronous communication receiver
PIN 11 (TXD): Serial asynchronous communication transmitter
PIN 12 (/INT0): External Interrupt 0 input
PIN 13 (/INT1): External Interrupt 1 input
PIN 14 (T0): Counter 0 clock input.
PIN 15 (T1): Counter 1 clock input
PIN 16 (/WR): Signal for writing to external (additional) RAM
PIN 17 (/RD): Signal for reading from external RAM PIN 18- PIN 19
(XTAL1, XTAL2): A quartz crystal which determines operating frequency is usually connected to these pins.
PIN 20 (GND): Ground
PIN 21- PIN 28 (PORT 2): In case external memory is used then the higher address byte, i.e. addresses A8-A15 will
appear on this port.
PIN 29 (/PSEN): If external ROM is used for storing program then it has a logic-0 value every time the microcontroller
reads a byte from memory.
EMBEDDED SYSTEM DESIGN 14

PIN 30 (ALE): Prior to each reading from external memory, the microcontroller will set the lower address byte (A0-A7)
on P0 and immediately after that activates the output ALE. Upon receiving signal from the ALE pin, the external
register memorizes the state of P0 and uses it as an address for memory chip. In the second part of the
microcontroller’s machine cycle, a signal on this pin stops being emitted and P0 is used now for data transmission
(Data Bus).

PIN 31 (/EA): By applying logic zero to this pin, P2 and P3 are used for data and address transmission with no regard to
whether there is internal memory or not. That means that even there is a program written to the microcontroller, it
will not be executed, the program written to external ROM will be used instead. Otherwise, by applying logic one to
the EA pin, the microcontroller will use both memories, first internal and afterwards external, up to end of address
space.

PIN 32- PIN 39 (PORT 0): Similar to port 2, if external memory is not used, these pins can be used as universal inputs or
outputs. Otherwise, P0 is configured as address output (A0-A7) when the ALE pin is at high level ‘1’ and as data output
(Data Bus), when logic zero ‘0’ is applied to the ALE pin.
PIN 40 (VCC): Power supply +5V

2.3 INPUT/OUTPUT PORTS (I/O PORTS)


All 8051 microcontrollers have 4 I/O ports, each consisting of
8 bits which can be configured as inputs or outputs. This means that
the user has on disposal in total of 32 input/output lines connecting
the microcontroller to peripheral devices.
A logic state on a pin determines whether it is configured as
input or output: 0=output, 1=input. If a pin on the microcontroller
needs to be configured as output, then logic zero (0) should be
applied to the appropriate bit on I/O port.
Similar to that, if a pin needs to be configured as
input, then a logic one (1) should be applied to the appropriate port.
In this way, as a side effect a voltage level on the appropriate pin will
be 5V. This may sound a bit confusing but everything becomes clear
after studying a simplified electronic circuit connected to one I/O pin.

INPUT/OUTPUT:
This is a simplified overview of what is connected to a pin inside the
microcontroller. It concerns all pins except those included in P0 which
do not have embedded pull-up resistor.
EMBEDDED SYSTEM DESIGN 15

OUTPUT-PIN:
Logic zero (0) is applied to a bit in the P register. By turning
output FE transistor on, the appropriate pin is directly connected to
ground.

INPUT-PIN:
Logic one (1) is applied to a bit in the P register. Output FE
transistor is turned off. The appropriate pin remains connected to voltage power supply through a pull-up resistor of
high resistance.

PORT 0:
It is specific to this port to have a double purpose. If external memory is used then the lower address byte
(addresses A0-A7) is applied on it. Otherwise, all bits on this port are configured as inputs or outputs. Another
characteristic is expressed when it is configured as output.

If any pin on this port is configured as input then it performs as if it “floats”. Such input has unlimited input
resistance and has no voltage coming from “inside”. When the pin is configured as output, it performs as “open drain”,
meaning that by writing 0 to some port’s bit, the appropriate pin will be connected to ground (0V). By writing 1, the
external output will keep on “floating”. In order to apply 1 (5V) on this output, an external pull-up resistor must be
embedded.

PORT 1:
This is a true I/O port, because there are no role assigning as it is the case with P0. Since it has embedded pull-
up resistors it is completely compatible with TTL circuits.
PORT 2:
Similar to P0, when using external memory, lines on this port occupy addresses intended for external memory
chip. This time it is the higher address byte with addresses A8-A15. When there is no additional memory, this port can
be used as universal input-output port similar by features to the port 1.
PORT 3:
Even though all pins on this port can be used as universal I/O port, they also have an alternative function.
Since each of these functions use inputs, then the appropriate pins have to be configured like that. In other words,
prior to using some of reserve port functions, a logical one must be written to the appropriate bit in the P3 register.
EMBEDDED SYSTEM DESIGN 16

2.4 8051 MEMORY ORGANISATION

The microcontroller memory is divided into Program Memory and Data Memory. Program Memory (ROM) is
used for permanent saving program being executed, while Data Memory (RAM) is used for temporarily storing and
keeping intermediate results and variables.
All 8051 microcontrollers have 16-bit addressing bus and can address 64 kb memory. It is neither a mistake
nor a big ambition of engineers who were working on basic core development. It is a matter of very clever memory
organization which makes these controllers a real “programmers’ tidbit“.

PROGRAM MEMORY:
The oldest models of the 8051 microcontroller family did not have internal program memory. It was added
from outside as a separate chip. These models are recognizable by their label beginning with 803 (for ex. 8031 or
8032). All later models have a few Kbytes ROM embedded, Even though it is enough for writing most of the programs,
there are situations when additional memory is necessary.
A typical example of it is the use of so called lookup tables. They are used in cases when something is too
complicated or when there is no time for solving equations describing some process.

HOW DOES THE MICROCONTROLLER HANDLE EXTERNAL MEMORY DEPENDS ON THE PIN /EA LOGIC STATE?

EA=0 -In this case, internal program memory is completely ignored; only a program stored in external memory is to be
executed.
EA=1 -In this case, a program from built-in ROM is to be executed first. Afterwards, the execution is continued by
reading additional memory.
EMBEDDED SYSTEM DESIGN 17

In both cases, P0 and P2 are not available to the user because they are used for data and address
transmission. Besides, the pins ALE and PSEN are used too.

DATA MEMORY:
As already mentioned, Data Memory is used for temporarily storing and keeping data and intermediate results
created and used during microcontroller’s operating. Besides, this microcontroller family includes many other registers
such as: hardware counters and timers, input/output ports, serial data buffers etc.
The previous versions have the total memory size of 256 locations, while for later models this number is
incremented by additional 128 available registers. In both cases, these first 256 memory locations (addresses 0-FFh)
are the base of the memory. First 128 registers and this part of RAM are divided in several blocks.
The first block consists of 4 banks each including 8 registers designated as R0 to R7. Prior to access them, a
bank containing that register must be selected. Next memory block (in the range of 20h to 2Fh) is bit- addressable,
which means that each bit being there has its own address from 0 to 7Fh.
Since there are 16 such registers, this block contains in total of 128 bits with separate addresses (The 0th bit
of the 20h byte has the bit address 0 and the 7th bit of the 2Fh byte has the bit address 7Fh). The third group of
registers occupies addresses 2Fh-7Fh (in total of 80 locations) and does not have any special purpose or feature.
EMBEDDED SYSTEM DESIGN 18

ADDITIONAL MEMORY BLOCK OF DATA MEMORY:


In order to satisfy the programmers’ permanent hunger for Data Memory, producers have embedded an
additional memory block of 128 locations into the latest versions of the 8051 microcontrollers. In order to keep
already existing 8-bit architecture and compatibility with other existing models a little trick has been used. Using trick
in this case means that additional memory block shares the same addresses with existing locations intended for the
SFRs (80h- FFh).

HOW TO EXTEND MEMORY?


In case on-chip memory is not enough, it is possible to add two external memory chips with capacity of 64Kb
each. I/O ports P2 and P3 are used for their addressing and data transmission. From the users’ perspective, everything
functions quite simple if properly connected because the most operations are performed by the microcontroller itself.
The 8051 microcontroller has two separate reading signals RD (P3.7) and PSEN (PIN 29). The first one is
activated byte from external data memory (RAM) should be read, while another one is activated to read byte from
external program memory (ROM). These both signals are active at logical zero (0) level. A typical example of such
memory extension using special chips for RAM and ROM is called Harvard architecture.
 When the program during execution encounters the instruction which resides in external memory (ROM), the
microcontroller will activate its control output ALE and set the first 8 bits of address (A0-A7) on P0. In this way, IC
circuit 74HCT573 which "lets in" the first 8 bits to memory address pins is activated.
 A signal on the pin ALE closes the IC circuit 74HCT573 and immediately afterwards 8 higher bits of address (A8-
A15) appear on the port. In this way, a desired location in additional program memory is completely addressed.
The only thing left over is to read its content.
 Pins on P0 are configured as inputs, the pin PSEN is activated and the microcontroller reads content from memory
chip. The same connections are used both for data and lower address byte.
EMBEDDED SYSTEM DESIGN 19

Similar occurs when it is a needed to read some location


from external Data Memory. Now, addressing is performed
in the same way, while reading or writing is performed via
signals which appear on the control outputs RD or WR.

SFRS (SPECIAL FUNCTION REGISTERS):


SFRs are a kind of control table used for running and
monitoring microcontroller’s operating. Each of these
registers, even each bit they include, has its name, address
in the scope of RAM and clearly defined purpose ( for
example: timer control, interrupt, serial connection etc.).
This is a general-purpose register which serves for
storing intermediate results during operating. A number (an
operand) should be added to the accumulator prior to
execute an instruction upon it. Once an arithmetical
operation is performed by the ALU, the result is placed into
the accumulator. If a data should be transferred from one register to another, it must go through accumulator.

A Register (Accumulator)
B REGISTER:
B register is used during multiply and divide operations which can be performed only upon numbers stored in
the A and B registers. All other instructions in the program can use this register as a spare accumulator (A).

R REGISTERS (R0-R7):
This is a common name for the total 8 general purpose registers (R0-
R7). Even they are not true SFRs; they deserve to be discussed here
because of their purpose. Which of the banks will be active depends on two
bits included in the PSW Register. The following example best illustrates the
useful purpose of these registers.
Suppose that mathematical operations on numbers previously
stored in the R registers should be performed:
(R1+R2) - (R3+R4). Obviously, a register for temporary storing results of
addition is needed. Everything is quite simple and the program is as
follows:
MOV A, R3 ; move number from R3 into
accumulator
ADD A, R4 ; add number from R4 to accumulator
MOV R5, A ; temporarily move the result from accumulator to R5
EMBEDDED SYSTEM DESIGN 20

MOV A, R1 ; move number from R1 into accumulator


ADD A, R2 ; add content of R2 to accumulator
SUBB A, R5 ; subtract content of R5 from accumulator

PSW REGISTER (PROGRAM STATUS WORD):

This is one of the most important SFRs. The Program Status Word (PSW) contains several status bits that
reflect the current state of the CPU. The ALU automatically changes some of register’s bits, which is usually used in
regulation of the program performing.

PARITY BIT (BIT 0): If a number of 1’s in the accumulator is odd then this bit will be automatically set (1), otherwise it
will be cleared (0).

BIT 1: This bit is intended for the future versions of the microcontrollers, so it is not supposed to be here.

OVERFLOW (BIT 2): occurs when the result of arithmetical operation is greater than 255 (decimal), so that it cannot be
stored in one register. In that case, this bit will be set (1).
If there is no overflow, this bit will be cleared (0).
RS1 RS2 Space in RAM
RS0, RS1 -REGISTER BANK SELECTS BITS (BIT 3, BIT 4): These two bits are
used to select one of the four register banks in RAM. By writing zeroes 0 0 Bank0 00h-07h
and ones to these bits, a group of registers R0-R7 is stored in one of four
banks in RAM. 0 1 Bank1 08h-0Fh

F0 - Flag 0. This is a general-purpose bit available to the user. 1 0 Bank2 10h-17h

1 1 Bank3 18h-1Fh
AC - Auxiliary Carry Flag is used for BCD operations only.

CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical
operations and shift instructions.

DPTR REGISTER (DATA POINTER)


EMBEDDED SYSTEM DESIGN 21

They consist of two separate registers: DPH (Data Pointer High) and (Data Pointer Low).Their 16 bits are used
for external memory addressing. They may be handled as a 16-bit register or as two independent 8-bit registers.
Besides; the DPTR Register is usually used for storing data and intermediate results which have nothing to do with
memory locations.

SP REGISTER (STACK POINTER):

A value of the Stack Pointer ensures that the Stack Pointer will point to valid RAM and permits Stack
availability. By starting each subprogram, the value in the Stack Pointer is incremented by 1. In the same manner, by
ending subprogram, this value is decremented by 1.
After any reset, the value 7 is written to the Stack Pointer, which means that the space of RAM reserved for
the Stack starts from this location. If another value is written to this register then the entire Stack is moved to a new
location in the memory.

P0, P1, P2, P3 - INPUT/OUTPUT REGISTERS

In case that external memory and serial communication system are not in use then, 4 ports within total of 32
input-output lines are available to the user for connection to peripheral environment. Each bit inside these ports
corresponds to the appropriate pin on the microcontroller.
This means that logic state written to these ports appears as a voltage on the pin (0 or 5 V). Naturally, while
reading, the opposite occurs – voltage on some input pins is reflected in the appropriate port bit.

2.5 8051 ADDRESSING MODES

Let’s begin this article with a simple question. “What is an addressing mode?” A simple question always has a
simple answer too. Addressing mode is a way to address an operand.  Operand means the data we are operating upon
it can be a direct address of memory, it can be register names, it can be any numerical data etc.
MOV A, #55H
Here the data “55H” is the operand, often known as source data. When this instruction is executed, the data
“55H” is moved to accumulator A. There are 5 different ways to execute this instruction and hence we say we have
got 5 addressing modes for 8051 they are:

1) IMMEDIATE ADDRESSING MODE


2) DIRECT ADDRESSING MODE 
3) REGISTER DIRECT ADDRESSING MODE
4) REGISTER INDIRECT ADDRESSING MODE 
5) INDEXED ADDRESSING MODE
EMBEDDED SYSTEM DESIGN 22

1) IMMEDIATE ADDRESSING MODE:


Let’s begin with an example:
MOV A, #6AH
In general we can write “MOV A, #data”. This addressing mode is named as “immediate” because it transfers
an 8-bit data immediately to the accumulator (A).
The op-code for MOV A, # data is 74H. The op-code is saved in program memory at 0202 address. The data
6AH is saved in program memory 0203.When the op-code 74H is read, the next step taken would be to transfer
whatever data at the next program memory address (here at 0203) to accumulator.
This instruction is of two bytes and is executed in one cycle. So after the execution of this instruction, program
counter will add 2 and move to o204 of program memory.
Note: The ‘#’ symbol before 6AH indicates that operand is a data (8 bit). If ‘#’ is not present then the
hexadecimal number would be taken as address.

2) DIRECT ADDRESSING MODE:


This is another way of addressing an operand. Here the address of the data is given as operand. Let us take an
example:
MOV A, 04H
Here 04H is the address of register 4 of register bank#0. When this instruction is executed, whatever data is
stored in register 04H is moved to accumulator. In the picture below we can see, register 04H holds the data 1FH.
So the data 1FH is moved to 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 accumulator instead 0f
1FH.As shown in picture below this is a 2 byte instruction which requires 1 cycle to complete. Program counter will
increment by 2 and stand in 0204. The op-code for instruction MOV A, address is E5H.
When the instruction at 0202 is executed (E5H), accumulator is made active and ready to receive data. The
program control goes to next address that is 0203 and look up the address of the location (04H) where the source data
(to be transferred to accumulator) is located. At 04H the control finds the data 1F and transfers it to accumulator and
hence the execution is completed.
EMBEDDED SYSTEM DESIGN 23

3) REGISTER DIRECT ADDRESSING MODE


In this addressing mode we use the register name directly. An example is shown below.
MOV A, R4
At a time registers can take value from R0, R1…to R7. You may already know there are 32 such registers. 
There are 4 register banks named 0, 1, 2 and 3. Each bank has 8 registers named from R0 to R7. At a time only one
register bank can be selected. Selection of register bank is made possible through a Special Function Register (SFR)
named Processor Status Word (PSW).

So in register direct addressing mode, data is transferred to accumulator from the register (based on which
register bank is selected. Take a look at the picture below.

So we see that op-code for MOV A, R4 is EC. The op-code is stored in program memory address 0202 and
when it is executed the control goes directly to R4 of the respected register bank If register bank #0 is selected then
the data from R4 of register bank #0 will be moved to accumulator. 04 H is the address of R4 of register bank #0.
Now please take a look at the dotted line. Here 2F is getting transferred to accumulator from data memory
location 0C H. Now understand that 0C H is the address location of Register 4 (R4) of register bank #1. Also keep in
mind that data at R4 of register bank #0 and register bank #1 (or even other banks) will not be same. This means using
register direct addressing mode can save program memory.
EMBEDDED SYSTEM DESIGN 24

4) REGISTER INDIRECT ADDRESSING MODE


So in this addressing mode, address of the data is given in the register operand.
MOV A, @R0
Here the value inside R0 is considered as an address, which holds the data to be transferred to accumulator.
Example: If R0 holds the value 20H, and we have a data 2F H stored at the address 20H, then the value 2FH will get
transferred to accumulator after executing this instruction.  See the picture below.
So the op-code for MOV A, @R0 is E6H. Assuming that register bank #0 is selected. So 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
accumulator.

Note: Only R0 and R1 are allowed to form a register indirect addressing instruction. In other words
programmer must make any instruction either using @R0 or @R1. All register banks are allowed.

5) INDEXED ADDRESSING MODE


Well let us see two examples first.
MOVC A, @A+DPTR
MOVC A, @A+PC
Where DPTR is data pointer and PC is program counter (both are 16 bit registers). Let’s take the first example.
MOVC A, @A+DPTR
The source operand is @A+DPTR and we know we will get the source data from this location. It is nothing but
adding contents of DPTR with present content of accumulator. This addition will result a new data which is taken as
the address of source data. The data at this address is then transferred to accumulator.  Take a look at the picture
below.
EMBEDDED SYSTEM DESIGN 25

The opcode for the instruction is 93H. DPTR holds the value 01FE, where 01 is located in DPH (higher 8 bits)
and FE is located in DPL (lower 8 bits). Accumulator now has the value 02H. A 16 bit addition is performed and now
01FE H+02 H results in 0200 H. whatever data is in 0200 H will get transferred to accumulator. The previous value
inside accumulator (02H) will get replaced with new data from 0200H. 

The other example MOVC A, @A+PC works the same way as above example. The only difference is, instead of
adding DPTR with accumulator, here data inside program counter (PC) is added with accumulator to obtain the target
address

UNIT-3: COUNTERS AND TIMERS


As explained in the previous chapter, the main oscillator of the microcontroller uses quartz crystal for its
operating. As the frequency of this oscillator is precisely defined and very stable, these pulses are the most suitable for
time measuring. In order to measure time between two events it is only needed to count up pulses from this oscillator.
That is exactly what the timer is doing.
The 8051 microcontrollers have 2 Timer/Counters called T0 and T1. As their names tell, their main purpose is
to measure time and count external events. Besides, they can be used for generating clock pulses used in serial
communication, i.e. Baud Rate.

TIMER:
As it is shown in the picture below, this timer is split into two registers – TH0 and TL0. The numbers these
registers include represent a lower and a higher byte of one 16-digit binary number.

This means that if the content of the Timer 0 is equal to 0 (T0=0) then both registers it includes will include 0.
Since the timers are virtually 16-bit registers, the greatest value that could be written to them is 65 535. In case of
exceeding this value, the timer will be automatically reset and afterwards that counting starts from 0. It is called
overflow.
Two registers TMOD and TCON are closely connected to this timer and control how it operates.
EMBEDDED SYSTEM DESIGN 26

TMOD REGISTER (TIMER MODE):


This register selects mode of the timers T0 and T1. As illustrated in the following picture, the lower 4 bits (bit3
– bit0) refer to the timer 0, while the higher 4 bits (bit7- bit4) refer to the timer 1. There are in total of 4 modes and
each of them is described here in this book.

 GATE1 starts and stops Timer 1 by means of a signal provided to the pin INT1 (P3.3)
 1 - Timer 1 operates only if the bit INT1 is set
 0 - Timer 1 operates regardless of the state of the bit INT 1
 C/T1 selects which pulses are to be counted up by the Timer/Counter
 1 - Timer counts pulses provided to the pin T1 (P3.5) or external clock
 0 - Timer counts pulses from internal oscillator
 T1M1, T1M0: These two bits select the Timer 1 operating mode.

M0 M1 MODE DESCRIPTION
0 0 0 13 bit mode
0 1 `1 16 bit mode

1 0 2 Auto-reload

1 1 3 Split mode

 GATE0 starts and stops Timer 1, using a signal provided to the pin INT0 (P3.2):
 1 - Timer 0 operates only if the bit INT0 is set
 0 - Timer 0 operates regardless of the state of the bit INT0
 C/T0 selects which pulses are to be counted up by the timer/counter 0:
 1 - Timer counts pulses provided to the pin T0(P3.4)
 0 - Timer counts pulses from internal oscillator
 T0M1, T0M0 These two bits select the Timer 0 operating mode. Similar to the previous table.

TCON - TIMER CONTROL REGISTER:


This is also one of the registers whose bits directly control timer operating.
Only 4 of all 8 bits this register has are used for timer control, while others are used for interrupt control which will be
discussed later.

 TF1 This bit is automatically set with the Timer 1 overflow


 TR1 This bit turns the Timer 1 on
 1 - Timer 1 is turned on
 0 - Timer 1 is turned off
EMBEDDED SYSTEM DESIGN 27

 TF0 This bit is automatically set with the Timer 0 overflow.


 TR0 This bit turns the timer 0 on
 1 - Timer 0 is turned on
 0 - Timer 0 is turned off

HOW TO START TIMER 0?


 Normally, first this timer and afterwards its mode should be selected. Bits which control that are resided in
the register TMOD:

 This means that timer0 operates in mode 1 and counts pulses from internal source whose frequency is equal
to 1/12 the quartz frequency. In order to enable the timer, turn it on:

 Immediately upon the bit TR0 is set, the timer starts operating. Assuming that a quartz crystal with frequency
of 12MHz is embedded, a number it contains will be incremented every microsecond.

 By counting up to 65.536 microseconds, the both registers that timer consists of will be set. The
microcontroller automatically reset them and the timer keeps on repeating counting from the beginning as far
as the bit’s value is logic one (1).

DETECTING TIMER 0 OVERFLOW:


 It is sufficient to register the moment they are reset, i.e.
when counting starts from 0. It is called overflow.
 When this has occurred, the bit TF0 from the register TCON
will be automatically set.
 The microcontroller is waiting for that moment in a way that
program will constantly check the state of this bit.
 First, it is needed to calculate a number that should be
written to the timer registers.
 This number should be written to the timer registers TH0 and
TL0:
 Once the timer is started it will continue counting from the
written number.
 Program instruction checks if the bit TF0 is set, which happens
at the moment of overflow, i.e. after exactly 50.000 machine
EMBEDDED SYSTEM DESIGN 28

cycles and 0.05 seconds respectively.


TIMER 0 IN MODE 0 (13-BIT TIMER):

When using this mode, the higher byte TH0 and only the first
5 bits of the lower byte TL0 are in use. Being configured in this
way, the Timer 0 uses only 13 of all 16 bits. With each new pulse
coming, the state of the lower register (that one with 5 bits) is
changed.
After 32 pulses received it becomes full and
automatically is reset, while the higher byte TH0 is incremented by
1. This action will be repeated until registers count up 8192
pulses. After that, both registers are reset and counting starts
from 0.

STEPS TO PROGRAM IN MODE 0:


1. Load the TMOD value
2. Load initial counting value to TL0/TL1 and TH0/TH1
3. Start the timer (TR0=1 / TR1=1)
4. Keep monitoring the timer flag (TF0/TF1)
5. If ‘1’ stop the timer (TR0=0 / TR1=0)
6. Clear the TF0/TF1 flag
7. Go back to step 2

EXAMPLE: PROGRAM TO TOGGLE PORT1 WITH DELAY GENERATED BY COUNTING FROM 0000H-1FFFH

#include<reg51.h>
void main()
{
TMOD=0X00;
while(1)
{
TL0=0;
TH0=0;
TR0=1;
while(TF0==0);
TR0=0;
TF0=0;
P1=~P1;
}
}
EMBEDDED SYSTEM DESIGN 29

TIMER 0 IN MODE 1(16 BIT TIMER):

All bits from the registers TH0 and TL0 are used in this
mode. That is why for this mode is being more commonly used.
Counting is performed in the same way as in mode 0, with
difference that the timer counts up to 65 536, i.e. as far as the
use of 16 bits allows.

(SAME STEPS AS THAT OF MODE 0)


EXAMPLE: PROGRAM TO TOGGLE PORT1 WITH DELAY GENERATED BY COUNTING FROM 0000H-FFFFH

#include<reg51.h>
void main()
{
TMOD=0X01;
while(1)
{
TL0=0;
TH0=0;
TR0=1;
while(TF0==0);
TR0=0;
TF0=0;
P1=~P1;
}
}

TIMER 0 IN MODE 2 (AUTO-RELOAD TIMER):


What does auto-reload mean? Simply, it means that such
timer uses only one 8-bit register for counting, but it never counts
from 0 but from an arbitrary chosen value (0- 255) saved in another
register. Suppose that for any reason it is continuously needed to
count up 55 pulses at a time from the clock generator.
When using mode 1 or mode 0, it is needed to write number
200 to the timer registers and check constantly afterwards whether
overflow occurred, i.e. whether the value 255 is reached by counting.
When it has occurred, it is needed to rewrite number 200 and
repeat the whole procedure. The microcontroller performs the same
procedure in mode 2 automatically. Namely, in this mode it is only
EMBEDDED SYSTEM DESIGN 30

register TL0 operating as a timer (normally 8-bit), while the value from which counting should start is saved in the TH0
register.

STEPS TO PROGRAM IN MODE 2:


1. Load the TMOD value
2. Load the TH registers
3. Start the timer
4. Keep monitoring the timer flag (TF)
5. Clear the TF flag
7. Go back to step 4

EXAMPLE: PROGRAM TO TOGGLE PORT1 WITH DELAY GENERATED BY COUNTING FROM 55H-FFH
#include<reg51.h>
void main ()
{
TMOD=0X02;
TH0=0X55;
TR0=1;
while (1)
{
while(TF0==0);
TF0=0;
P1=~P1;
}
}

TIMER 0 IN MODE 3 (SPLIT TIMER):


By configuring Timer 0 to operate in Mode 3, the 16-bit counter
consisting of two registers TH0 and TL0 is split into two independent 8-
bit timers. In addition, all control bits which belonged to the initial
Timer 1 (consisting of the registers TH1 and TL1), now control newly
created Timer 1.
The only application of this mode is in case two independent
'quick' timers are used and the initial Timer 1 whose operating is out of
control is used as baud rate generator

TIMER 1:
Referring to its characteristics, this timer is “a twin brother “to the Timer 0. This means that they have the
same purpose, their operating is controlled by the same registers TMOD and TCON and both of them can operate in
one of 4 different modes.
EMBEDDED SYSTEM DESIGN 31

COUNTER PROGRAMMING:
STEPS TO COUNT AN EXTERNAL PULSE USING COUNTER 0 IN MODE 1:
1. Load the TMOD value
2. Load initial counting value to TL0/TL1 and TH0/TH1
3. Start the timer (TR0=1 / TR1=1)
4. Keep monitoring the timer flag (TF0/TF1)
5. If ‘0’ send the count values from TH0 & TL0 to any ports
6. If ‘1’ stop the timer (TR0=0 / TR1=0)
7. Clear the TF0/TF1 flag
8. Go back to step 2

EXAMPLE: PROGRAM TO STORE THE COUNT VALUE OF TH0 IN P1 AND TL0 IN P2

#include<reg51.h>
void main()
{
TMOD=0X05;
while(1)
{
TL0=0;
TH0=0;
TR0=1;
while(TF0==0)
{
P1=TH0;
P2=TL0;
}
TR0=0;
TF0=0;
}
EMBEDDED SYSTEM DESIGN 32

UNIT-4: SERIAL COMMUNICATION

UART (UNIVERSAL ASYNCHRONOUS RECEIVER AND TRANSMITTER)


One of the features that makes this microcontroller so powerful is an integrated UART, better known as a
serial port. It is a duplex port, which means that it can transmit and receive data simultaneously.
All the programmer needs to do is to simply select serial port mode and baud rate. When the programmer is
such configured, serial data sending is done by writing to the register SBUF while data receiving is done by reading the
same register.

Serial port should be configured prior to being used. That determines how many bits one serial “word”
contains, what the baud rate is and what the pulse source for synchronization is. All bits controlling this are stored in
the SFR Register SCON (Serial Control).

SCON REGISTER (SERIAL PORT CONTROL REGISTER)

 SM0 , SM1- bit selects mode


 SM2 - bit is used in case that several microcontrollers share the same interface. In normal circumstances this
bit must be cleared.
 REN - bit enables data receiving via serial communication and must be set in order to enable it.
 TB8 - Since all registers in microcontroller are 8-bit registers, this bit solves the problem of sending the 9th bit
in modes 2 and 3.
 RB8 - bit has the same purpose as the bit TB8 but this time on the receiver side.
 TI - bit is automatically set at the moment the last bit of one byte is sent when the USART operates as a
transmitter. Bit must be clear from within the program.
 RI - bit is automatically set once one byte has been received. Everything functions in the similar way as in the
previous case but on the receive side. This bit must also be also cleared from within the program.

As seen, serial port mode is selected by combining the bits SM0 and SM2 :
SM0 SM1 Mode Description Baud Rate
0 0 0 8-bit Shift Register 1/12 the quartz frequency
0 1 1 8-bit UART Determined by the timer 1
EMBEDDED SYSTEM DESIGN 33

1 0 2 9-bit UART 1/32 the quartz frequency (1/64 the quartz


frequency)
1 1 3 9-bit UART Determined by the timer 1

MAX232

MAX232 is used to convert voltage signals to TTL voltage levels that will be accepted to 8051’s TXD and RXD
pins.it uses +5v power source which is the same as that of 8051.

MODE 0:

TRANSMIT - Data transmission in form of pulse


train automatically starts on the pin RXD at the moment the
data has been written to the SBUF register.In fact, this process
starts after any instruction being performed on this register.
Upon all 8 bits have been sent, the bit TI in the SCON
register is automatically set.
EMBEDDED SYSTEM DESIGN 34

RECEIVE - Starts data receiving through the pin RXD once two necessary conditions are met: bit REN=1 and RI=0 (both
bits reside in the SCON register). Upon 8 bits have been received, the bit RI (register SCON) is automatically set, which
indicates that one byte is received.

Since, there are no START and STOP bits or any other bit except data from the SBUF register, this mode is
mainly used on shorter distance where the noise level is minimal and where operating rate is important.

MODE 1:

In Mode1,10 bits are transmitted through TXD or received through RXD in the following manner: a START bit
(always 0), 8 data bits (LSB first) and a STOP bit (always 1) last.

TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the data has
been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the SCON register.

RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The condition is that bit
REN=1 and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon receiving has
been completed.The Baud rate in this mode is determined by the timer 1 overflow time.
EMBEDDED SYSTEM DESIGN 35

MODE 2:

In mode 2, 11 bits are sent through TXD or received through RXD: a START bit (always 0), 8 data bits (LSB first),
additional 9th data bit and a STOP bit (always 1) last. On transmit, the 9th data bit is actually the TB8 bit from the
SCON register.

TRANSMIT - A sequence for data transmission via serial communication is automatically started upon the data has
been written to the SBUF register. End of 1 byte transmission is indicated by setting the TI bit in the SCON register.

RECEIVE - Receiving starts as soon as the START bit (logic zero (0)) appears on the pin RXD. The condition is that bit
REN=1and bit RI=0. Both of them are stored in the SCON register. The RI bit is automatically set upon receiving has
been completed.

MODE 3:
Mode 3 is the same as Mode 2 except the baud rate. In Mode 3 is variable and can be selected.

BAUD RATE:
Baud Rate is defined as a number of send/received bits per second. In case the UART is used, baud rate
depends on: selected mode, oscillator frequency and in some cases on the state of the bit SMOD stored in the SCON
register.
Timer 1 as a baud rate generator:
Timer 1 is usually used as a baud rate generator because it is easy to adjust various baud rate by the means of this
timer. The whole procedure is simple:
 First, Timer 1 overflow interrupt should be disabled
EMBEDDED SYSTEM DESIGN 36

 Timer T1 should be set in auto-reload mode

Depending on necessary baud rate, in order to obtain some of the standard values one of the numbers from
the table should be selected. That number should be written to the TH1 register.

Baud Rate Fosc. (MHz) Bit SMOD


11.0592 12 14.7456 16 20
150 40 h 30 h 00 h 0
300 A0 h 98 h 80 h 75 h 52 h 0
600 D0 h CC h C0 h BB h A9 h 0
1200 E8 h E6 h E0 h DE h D5 h 0
2400 F4 h F3 h F0 h EF h EA h 0
4800 F3 h EF h EF h 1
4800 FA h F8 h F5 h 0
9600 FD h FC h 0
9600 F5 h 1
19200 FD h FC h 1
38400 FE h 1
76800 FF h 1

MULTIPROCESSOR COMMUNICATION:
A useful application of this bit is in communication between two microcontrollers, i.e. multiprocessor
communication.
This feature is enabled by setting the SM2 bit in the SCON register. The consequence is the following: when
the STOP bit is ready, indicating end of message, the serial port interrupt will be requested only in case the bit RB8 = 1
(the 9th bit).Suppose that there are several connected microcontrollers having to exchange data.
That means that each of them must have its address. The point is that each address sent via serial
communication has the 9th bit set (1), while data has it cleared (0). If the microcontroller A should send data to the
microcontroller C then it at will place first send address of C and the 9th bit set to 1. That will generate interrupt and
all microcontrollers will check whether they are called.

Here TIMER1 MODE2 is used as a baud rate generator.


EMBEDDED SYSTEM DESIGN 37

STEPS TO CALCULATE THE VALUE TO BE LOADED TO TH1:

28800 / 9600 (required baud rate)=3


256 (maximum value for mode 2) – 3 (previous result) = 253 (FDh)

TRANSMIT PROGRAM:
STEPS TO TRANSMIT TO THE VIRTUAL TERMINAL:
1. Load the SCON value
2.Load the TMOD value
3.Load initial counting value to TH1
4.Start the timer (TR1=1)
5.Load the value to be transmitted to the SBUF register
6.Keep monitoring the transmit flag (TI)
7.If ‘1’ clear the TI flag
8.Go back to step 5

EXAMPLE: PROGRAM TO TRANSMIT ‘A’ TO THE VIRTUAL TERMINAL.


#include<reg51.h>
void main()
{
SCON=0X50;
TMOD=0X20;
TH1=0XFD;
TR1=1;
while(1)
{
SBUF=’A’;
while(TI==0);
TI=0;
}
}
EMBEDDED SYSTEM DESIGN 38

RECEIVE PROGRAM:
STEPS TO RECEIVE FROM THE VIRTUAL TERMINAL:
1. Load the SCON value
2. Load the TMOD value
3. Load initial counting value to TH1
4. Start the timer (TR1=1)
5. Keep monitoring the receive flag (RI)
6. If ‘1’ store the received value in a location
7. Clear the RI flag
8. Go back to step 5

EXAMPLE: PROGRAM TO RECEIVE FROM THE VIRTUAL TERMINAL AND STORE TO IN P1

#include<reg51.h>
void main()
{
SCON=0X50;
TMOD=0X20;
TH1=0XFD;
TR1=1;
while(1)
{
while(RI==0);
P1=SBUF;
RI=0;
}
}
EMBEDDED SYSTEM DESIGN 39

UNIT-5: 8051 INTERRUPTS


There are five interrupt sources for the 8051, which means that they can recognize 5 different events that can
interrupt regular program execution. Each interrupt can be enabled or disabled by setting bits in the IE register. Also,
as seen from the picture below the whole interrupt system can be disabled by clearing bit EA from the same register.

Now, one detail should be explained which is not completely obvious but refers to external interrupts- INT0
and INT1. Namely, if the bits IT0 and IT1 stored in the TCON register are set, program interrupt will occur on changing
logic state from 1 to 0. If these bits are cleared, the same signal will generate interrupt request and it will be
continuously executed as far as the pins are held low.

IE REGISTER (INTERRUPT ENABLE):

 EA - bit enables or disables all other interrupt sources


 0 - any interrupt request is ignored
 1 - enables all interrupts requests which are individually enabled
 ES - bit enables or disables serial communication interrupt (UART)
 0 - UART System cannot generate interrupt
 1 - UART System enables interrupt
 ET1 - bit enables or disables Timer 1 interrupt
 0 - Timer 1 cannot generate interrupt
 1 - Timer 1 enables interrupt
 EX1 - bit enables or disables INT 0 pin external interrupt
 0 - change of the pin INT0 logic state cannot generate interrupt
 1 - enables external interrupt at the moment of changing the pin INT0 state
 ET0 - bit enables or disables timer 0 interrupt
 0 - Timer 0 cannot generate interrupt
 1 - enables timer 0 interrupt
 EX0 - bit enables or disables INT1 pin external interrupt
 0 - change of the INT1 pin logic state cannot cause interrupt
 1 - enables external interrupt at the moment of changing the pin INT1 state
EMBEDDED SYSTEM DESIGN 40

INTERRUPT PRIORITIES: It is not possible to predict when an interrupt will be required. For that reason, if several
interrupt are enabled. It can easily occur that while one of them is in progress, another one is requested. In such
situation, there is a priority list making the microcontroller know whether to continue operating or meet a new
interrupt request.
The priority list consists of 3 levels:
1. Reset: The absolute master of the situation. If a request for Reset omits, everything is stopped and the
microcontroller starts operating from the beginning.
2. Interrupt priority 1: It can be stopped by Reset only.
3. Interrupt priority 0: It can be stopped by both Reset and interrupt priority 1.

Which one of these existing interrupt sources has higher and which one has lower priority is defined in the IP
Register (Interrupt Priority Register). According to that, there are several possibilities:
 Once an interrupt service begins. It cannot be interrupted by another interrupt at the same or lower priority
level, but only by a higher priority interrupt.
 If two interrupt requests, at different priority levels, arrive at the same time then the higher priority interrupt
is serviced first.
 If the both interrupt requests, at the same priority level, occur one after another, the one who came later has
to wait until routine being in progress ends.
 If two interrupts of equal priority requests arrive at the same time then the interrupt to be serviced is selected
according to the following priority list :
 External interrupt INT0 (interrupt 0)
 Timer 0 interrupt (interrupt 1)
 External Interrupt INT1 (interrupt 2)
 Timer 1 interrupt (interrupt 3)
 Serial Communication Interrupt (interrupt 4)

IP REGISTER (INTERRUPT PRIORITY):


The IP register bits specify the priority level of each interrupt (high=’1’ or low =’0’ priority).

 PS - Serial Port Interrupt priority bit


 PT1 - Timer 1 interrupt priority
 PX1 - External Interrupt INT1 priority
 PT0 - Timer 0 Interrupt Priority
 PX0 - External Interrupt INT0 Priority

HANDLING INTERRUPT:
Once some of interrupt requests arrives, everything occurs according to the following order:
1. Instruction in progress is ended
2. The address of the next instruction to execute is pushed on the stack
3. Depending on which interrupt is requested, one of 5 vectors (addresses) is written to the program counter in
accordance to the following table:
EMBEDDED SYSTEM DESIGN 41

Interrupt Source Vector (address)


IE0 3h
TF0 Bh
TF1 1B h
RI, TI 23 h
All addresses are in hexadecimal format
4. The appropriate subroutines processing interrupts should be located at these addresses. Instead of them,
there are usually jump instructions indicating the location where the subroutines reside.

5. When interrupt routine is executed, the address of the next instruction to execute is popped from the stack to
the program counter and interrupted program continues operating from
where it left off.

RESET:
Reset occurs when the RS pin is supplied with a positive pulse in duration
of at least 2 machine cycles.
After that, the microcontroller generates internal reset signal during which
all SFRs, excluding SBUF registers, Stack Pointer and ports are reset.
Depending on device purpose and environment it is in, on power-on reset
it is usually push button or circuit or both connected to the RS pin.
One of the simplest circuit providing secure reset at the moment of
turning power on is shown on the picture.

PROGRAMMING INTERRUPTS:
EXAMPLE: PROGRAM TO TOGGLE P1 USING TIMER 0 MODE 1 AND SIMULTANEOUSLY MOVE THE VALUE FROM P2
TO P0 #include<reg51.h>
void timer0() interrupt 1
{
P1=~P1;
TH0=0;
TL0=0;
return;
}
void main()
{
IE=0X82;
TMOD=0X01;
TH0=0;
TL0=0;
TR0=1;
while(1)
{
EMBEDDED SYSTEM DESIGN 42

P0=P2;
}}

8051 MICROCONTROLLER POWER CONSUMPTION


CONTROL:
Conditionally said microcontroller is the most part of its
“lifetime” is inactive for some external signal in order to takes its role in a
show. It can make a great problem in case batteries are used for power
supply. In extremely cases, the only solution is to put the whole
electronics to sleep in order to reduce consumption to the minimum.
A typical example of this is remote TV controller: it can be out
of use for months but when used again it takes less than a second to
send a command to TV receiver. While normally operating, the
AT89S53 uses current of approximately 25mA, which shows that it is
not too sparing microcontroller.
Anyway, it doesn’t have to be always like this, it can easily switch the operation mode in order to reduce its
total consumption to approximately 40uA. Actually, there are two power-saving modes of operation: Idle and Power
Down.

IDLE MODE :
Immediately upon instruction which sets the bit IDL in the PCON register, the microcontroller turns off the
greatest power consumer- CPU unit while peripheral unit serial port, timers and interrupt system continue operating
normally consuming 6.5mA. In Idle mode, the state of all registers and I/O ports is remains unchanged.
In order to terminate the idle mode and make the microcontroller operate normally, it is necessary to enable
and execute any interrupt or reset. Then, the IDL bit is automatically cleared and the program continues executing
from instruction following that instruction which has set the IDL bit.

POWER DOWN MODE:


When the bit PD in the register PCON is set from within the program, the microcontroller is set to Power down
mode.
It turns off its internal oscillator reducing drastically consumption in that way. In power- down mode the
microcontroller can operate using only 2V power supply while the total power consumption is less than 40uA. The only
way to get the microcontroller back to normal mode is reset.
During Power Down mode, the state of all SFR registers and I/O ports remains unchanged, and after the
microcontroller is put get into the normal mode, the content of the SFR register is lost, but the content of internal
RAM is saved. Reset signal must be long enough approximately 10mS in order to stabilize quartz oscillator operating.

PCON-REGISTER
The purpose of the Register PCON bits:
 SMOD : By setting this bit baud rate is doubled.
 GF1 :General-purpose bit (available for use).
 GF1 :General-purpose bit (available for use).
EMBEDDED SYSTEM DESIGN 43

 GF0 :General-purpose bit (available for use).


 PD : By setting this bit the microcontroller is set into Power Down mode.
 IDL : By setting this bit the microcontroller is set into idle mode.

ALPHABETICAL LIST OF INSTRUCTIONS (FOR ASSEMBLY PROGRAMMING):


 ACALL : Absolute Call
 ADD, ADDC : Add Accumulator (With Carry)
 AJMP : Absolute Jump
 ANL : Bitwise AND
 CJNE : Compare and Jump if Not Equal
 CLR : Clear Register
 CPL : Complement Register
 DA : Decimal Adjust
 DEC : Decrement Register
 DIV : Divide Accumulator by B
 DJNZ : Decrement Register and Jump if Not Zero
 INC : Increment Register
 JB : Jump if Bit Set
 JBC : Jump if Bit Set and Clear Bit
 JC : Jump if Carry Set
 JMP : Jump to Address
 JNB : Jump if Bit Not Set
 JNC : Jump if Carry Not Set
 JNZ : Jump if Accumulator Not Zero
 JZ : Jump if Accumulator Zero
 LCALL : Long Call
 LJMP : Long Jump
 MOV : Move Memory
 MOVC : Move Code Memory
 MOVX : Move Extended Memory
 MUL : Multiply Accumulator by B
 NOP : No Operation
 ORL : Bitwise OR
 POP : Pop Value From Stack
 PUSH : Push Value Onto Stack
 RET : Return From Subroutine
 RETI : Return From Interrupt
 RL : Rotate Accumulator Left
 RLC : Rotate Accumulator Left Through Carry
 RR : Rotate Accumulator Right
 RRC : Rotate Accumulator Right Through Carry
 SETB : Set Bit
 SJMP : Short Jump
 SUBB : Subtract From Accumulator With Borrow
 SWAP : Swap Accumulator Nibbles
EMBEDDED SYSTEM DESIGN 44

 XCH : Exchange Bytes


 XCHD : Exchange Digits
 XRL : Bitwise Exclusive OR

REVIEW QUESTIONS:

a) Write one instruction each using the following addressing modes.


1. IMMEDIATE 2.REGISTER 3.REGISTER INDIRECT 4.DIRECT
b) What does the following instruction do?
MOV A, 1FH
c) Which timer & mode of the 8051 is used to set the baud rate?
d) To transfer a byte of data serially it must be in register ________
e) What is the function of MAX232 chip?
f) TF0 and TF1 are a part of register_________________.
g) Which pins are used as external clock inputs?
h) Is TMOD a bit-addressable register? (T/F)
i) What vector address in the interrupt vector table is assigned to TIMER 1?
j) Mention the priority of all the interrupts of 8051

PROGRAMS:

a) Write a code to copy 10 bytes of data starting at ROM address 400H to RAM locations starting at 30H
b) Assuming that XTAL=11.0592 MHz , program TIMER 0 to generate a square wave of 50 Hz using MODE 2
c) Program TIMER 0 to be an event counter. Use mode 2 and display the binary count on P1 &P2 continuously. Set
the initial count to be 20000.
d) Program 8051 to transmit your name continuously at 9600 baud rate.
e) Write an 8051 program to receive any two inputs and store it in PORT1 and PORT2. Then receive any letter, if ‘A’
add the two inputs , if ‘S’ subtract, if ‘M’ multiply, if ‘D’ divide and display the result in PORT 3, if any other key is
pressed transmit “INVALID KEY PRESSED” .
f) Write a program to generate a square wave of 1 second in P1.2 using TIMER0 MODE 1
And simultaneously perform xor operation of PORT 2 & PORT 3 and display the result in PORT 0
EMBEDDED SYSTEM DESIGN 45

PIC
MICROCONTROLLER
EMBEDDED SYSTEM DESIGN 46

UNIT 6: INTRODUCTION TO PIC

PIC microcontrollers are popular processors developed by Microchip Technology with built-in RAM, memory,
internal bus, and peripherals that can be used for many applications. PIC originally stood for “Programmable
Intelligent Computer” but is now generally regarded as a “Peripheral Interface Controller”.

TYPES OF PIC:
PIC microcontrollers are broken up into two major categories:
1. 8-BIT MICROCONTROLLERS
2. 16-BIT MICROCONTROLLERS
Each category is further subdivided into product families as shown in the following table:
8-bit MCU Product Family 16-bit MCU Product Family:
PIC10XX, PIC12XX, PIC14XX, PIC16XX, PIC18XX
The microcontrollers in the PIC10 through PIC14 families are considered low-end microcontrollers. PIC
microcontrollers in the PIC16 and PIC18 families are considered mid-level microcontrollers while 16-bit PICs are
considered high-end microcontrollers.

HIGH PERFORMANCE RISC CPU:

 C compiler optimized architecture/instruction set


 Linear program memory addressing to 32 Kbytes
 Linear data memory addressing to 1.5 Kbytes
 Up to 10 MIPs operation
 DC - 40 MHz osc./clock input
 4 MHz - 10 MHz osc./clock input with PLL active
 16-bit wide instructions, 8-bit wide data path
 Priority levels for interrupts

PERIPHERAL FEATURES:
 Three external interrupt pins
 Timer0 module: 8-bit/16-bit timer/counter with 8-bit programmable prescaler
EMBEDDED SYSTEM DESIGN 47

 Timer1 module: 16-bit timer/counter


 Timer2 module: 8-bit timer/counter with 8-bit period register
 Timer3 module: 16-bit timer/counter
 Secondary oscillator clock option - Timer1/Timer3
 Two Capture/Compare/PWM (CCP) modules. CCP pins that can be configured as:
 Capture input: capture is 16-bit,max. resolution 6.25 ns (TCY/16)
 Compare is 16-bit, max. resolution 100 ns (TCY)
 PWM output: PWM resolution is 1- to 10-bit, max. PWM freq. @: 8-bit resolution = 156 kHz10-
bit resolution = 39 kHz
 Two modes of operation:
 3-wire SPI™ (supports all 4 SPI modes)
 I2C™ Master and Slave mode
 Addressable USART module:
 Supports RS-485 and RS-232
 Parallel Slave Port (PSP) module

ANALOG FEATURES:
 Compatible 10-bit Analog-to-Digital Converter module (A/D) with:
 Fast sampling rate
 Conversion available during SLEEP
 Linearity ≤ 1 LSB
 Programmable Low Voltage Detection (PLVD)

SPECIAL MICROCONTROLLER FEATURES:


 100,000 erase/write cycle Enhanced FLASH program memory typical
 1,000,000 erase/write cycle Data EEPROM memory
 FLASH/Data EEPROM Retention: > 40 years
 Self-reprogrammable under software control
 Power-on Reset (POR), Power-up Timer (PWRT) & Oscillator Start-up Timer (OST)
 Watchdog Timer (WDT) with its own On-Chip RC
 Power saving SLEEP mode
 Selectable oscillator options including:
 4X Phase Lock Loop (of primary oscillator)
 Secondary Oscillator (32 kHz) clock input
 Single supply 5V In-Circuit Serial Programming™

CMOS TECHNOLOGY:
 Low power, high speed FLASH/EEPROM technology
 Fully static design
 Wide operating voltage range (2.0V to 5.5V)
 Industrial and Extended temperature ranges
 Low power consumption:
 < 1.6 mA typical @ 5V, 4 MHz
 25 μA typical @ 3V, 32 kHz
 < 0.2 μA typical stand by current
EMBEDDED SYSTEM DESIGN 48

UNIT 7: PIC18F452 DEVICE OVERVIEW


EMBEDDED SYSTEM DESIGN 49

DEVICE FEATURES:
EMBEDDED SYSTEM DESIGN 50

PIN CONFIGURATION:
EMBEDDED SYSTEM DESIGN 51

PIN NAME PIN NO. DESCRIPTION

MCLR/VPP 1 Master Clear I/P, High Voltage Pin

OSC1/CLKI 13 Oscillator Crystal Or External Clock I/P

Port A Is A Bi-Directional I/O Port

RA0/AN0 2 Digital I/O, Analog I/P 0

RA1/AN1 3 Digital I/O, Analog I/P 1

RA2/AN2/VREF- 4 Digital I/O, Analog I/P 2, A/D Reference Voltage(Low)

RA3/AN3/VREF+ 5 Digital I/O, Analog I/P 3, A/D Reference Voltage(High)

RA4/T0CKI 6 Digital I/O,Timer0 External Clock I/P

RA5/AN4/SS/LVDIN 7 Digital I/O, Analog I/P 4, Slave Select I/P,Low Volt

OSC2/CLKO/RA6 14 Oscillator Crystal,Clk O/P, Digital I/O

Port B Is A Bi-Directional I/O Port. It Can Be Software Programmed For Interrupts

RB0/INT0 33 Digital I/O, External Interrupt 0

RB1/INT1 34 Digital I/O, External Interrupt 1


EMBEDDED SYSTEM DESIGN 52

RB2/INT2 35 Digital I/O, External Interrupt 2

RB3/CCP2 36 Digital I/O, Capture2 I/P, Compare 2 O/P, PWM2 O/P

RB4 37 Digital I/O

RB5 38 Digital I/O

RB6 39 Digital I/O

RB7 40 Digital I/O

Port C is a Bi-Directional I/O Port.

RC0/T1OS0/T1CKI 15 Digital I/O, Timer1 Osc O/P, Timer1 External Clk I/P

RC1/T1OS1/CCP2 16 Digital I/O, Timer1 Osc O/P, Capture2 I/P, Compare2 O/P, PWM2
O/P

RC2/CCP1 17 Digital I/O, Timer1 Osc O/P, Capture1 I/P, Compare1 O/P, PWM1
O/P

RC3/SCK/SCL 18 Digital I/O,Serial Clk I/O For SPI & IC2

RC4/SDI/SDA 23 Digital I/O,Serial Clk input For SPI & I/O for IC2

RC5/SD0 24 Digital I/O,SPI Data out

RC6/TX/CK 25 Digital I/O, USART Asynchronous Transmit.


USART Synchronous Clock

RC7/RX/DT 26 Digital I/O,USART Asynchronous Receive.


USART Synchronous Data
Port D is a Bi-Directional I/O Port or a Parallel slave port.

RD0/PSP0 19 Digital I/O, Parallel Slave Port Data.

RD1/PSP1 20 Digital I/O, Parallel Slave Port Data.

RD2/PSP2 21 Digital I/O, Parallel Slave Port Data.

RD3/PSP3 22 Digital I/O, Parallel Slave Port Data.

RD4/PSP4 27 Digital I/O, Parallel Slave Port Data.

RD5/PSP5 28 Digital I/O, Parallel Slave Port Data.

RD6/PSP6 29 Digital I/O, Parallel Slave Port Data.

RD7/PSP7 30 Digital I/O, Parallel Slave Port Data.


EMBEDDED SYSTEM DESIGN 53

Port D is a Bi-Directional I/O Port.


RE0/RD/AN5 8 Digital I/O, Read control for parallel slave port
Analog input 5.
RE1/WR/AN6 9 Digital I/O, Write control for parallel slave port
Analog input 6.
RE2/CS/AN7 10 Digital I/O, Chip select control for parallel slave port
Analog input 7.
VSS 12,31 Ground reference for logic and I/O pins.

VDD 11, 32 Positive supply for logic and I/O pins.

MEMORY ORGANISATION:
There are three memory blocks in Enhanced MCU devices. These memory blocks are:
 Program Memory
 Data RAM
 Data EEPROM

PROGRAM MEMORY ORGANIZATION:


A 21-bit program counter is capable of addressing the 2-Mbyte program memory space. The PIC18F452
has 32 Kbytes of FLASH memory. The RESET vector address is at 0000h and the interrupt vector addresses are at
0008h and 0018h.

INSTRUCTION FLOW/PIPELINING:
An “Instruction Cycle” consists of four Q cycles (Q1, Q2, Q3 and Q4). The instruction fetch and execute
are pipelined such that fetch takes one instruction cycle, while decode and execute takes another instruction
cycle. However, due to the pipelining, each instruction effectively executes in one cycle. If an instruction causes
the program counter to change (e.g., GOTO) then two cycles are required to complete the instruction
EMBEDDED SYSTEM DESIGN 54

A fetch cycle begins with the program counter (PC) incrementing in Q1. In the execution cycle, the
fetched instruction is latched into the “Instruction Register” (IR) in cycle Q1. This instruction is then decoded
and executed during the Q2, Q3, and Q4 cycles. Data memory is read during Q2 (operand read) and written
during Q4 (destination writes).

DATA MEMORY ORGANIZATION:


The data memory is implemented as static RAM. Each register in the data memory has a 12-bit address,
allowing up to 4096 bytes of data memory. The data memory map is divided into as many as 16 banks that
contain 256 bytes each. The lower 4 bits of the Bank Select Register select which bank will be accessed.
The data memory contains Special Function Registers (SFR) and General Purpose Registers (GPR). The
SFRs are used for control and status of the controller and peripheral functions, while GPRs are used for data
storage and scratch pad operations in the user’s application. GPRs start at the first location of Bank 0 and grow
upwards.
GENERAL PURPOSE REGISTER FILE:
The register file can be accessed either directly or indirectly. Indirect addressing operates using a File
Select Register and corresponding Indirect File Operand. GPRs are not initialized by a Power-on Reset and are
unchanged on all other RESETS. Data RAM is available for use as GPR registers by all instructions. The top half of
Bank 15 contains SFRs. All the other banks of data memory contain GPR registers, starting with Bank 0.
SPECIAL FUNCTION REGISTERS:
The Special Function Registers (SFRs) are registers used by the CPU and Peripheral Modules for
controlling the desired operation of the device. The SFRs can be classified into two sets; those associated with
the “core” function and those related to the peripheral functions. The SFRs are typically distributed among the
peripherals whose functions they control. The unused SFR locations will be unimplemented and read as '0's.
EMBEDDED SYSTEM DESIGN 55

STATUS REGISTER:
The STATUS register contains the arithmetic status of the ALU. The STATUS register can be the
destination for any instruction, as with any other register. If the STATUS register is the destination for an
instruction that affects the Z, DC, C, OV, or N bits, then the write to these five bits is disabled. These bits are set
or cleared according to the device logic.

BIT BIT DESCRIPTION


NAME NO.
- 7-5 Unimplemented: Read as '0'

N 4 Negative bit: 1 = Result was negative


0 = Result was positive
OV 3 Overflow bit: 1 = Overflow occurred
0 = No overflow occurred
Z 2 Zero bit: 1 = The result is zero
0 = The result is not zero
DC 1 Digit carry/borrow bit:
1= A carry-out from the 4th low order bit of the result occurred
0 = No carry-out from the 4th low order bit of the result
C 0 Carry/borrow bit:
1 = A carry-out from the MSB of the result occurred
0 = No carry-out from the MSB of the result occurred

RCON REGISTER:
The Reset Control (RCON) register contains flag bits that allow differentiation between the sources of a
device RESET. These flags include the TO, PD, POR, BOR and RI bits. This register is readable and writable.
EMBEDDED SYSTEM DESIGN 56

BIT BIT DESCRIPTION


NAME NO.
IPEN 7 Interrupt Priority Enable bit
1 = Enable priority levels on interrupts
0 = Disable priority levels on interrupts
- 6-5 Unimplemented: Read as '0'
RI 4 RESET Instruction Flag bit:
1 = The RESET instruction was not executed
0 = The RESET instruction was executed causing a device RESET
TO 3 Watchdog Time-out Flag bit:
1 = After power-up, CLRWDT instruction, or SLEEP instruction
0 = A WDT time-out occurred
PD 2 Power-down Detection Flag bit:
1 = After power-up or by the CLRWDT instruction
0 = By execution of the SLEEP instruction
POR 1 Power-on Reset Status bit:
1 = A Power-on Reset has not occurred
0 = A Power-on Reset occurred
BOR 0 Brown-out Reset Status bit:
1 = A Brown-out Reset has not occurred
0 = A Brown-out Reset occurred
EMBEDDED SYSTEM DESIGN 57

UNIT 8: I/O PORTS


Depending on the device selected, there are either five ports or three ports available. Some pins of the
I/O ports are multiplexed with an alternate function from the peripheral features on the device. In general,
when a peripheral is enabled, that pin may not be used as a
General purpose I/O pin. Each port has two registers for its operation.
These registers are:
 TRIS register (data direction register)
 PORT register (reads the levels on the pins of the device)

PORTA AND TRISA REGISTERS:


PORTA is a 7-bit wide, bi-directional port. The corresponding Data Direction register is TRISA. Setting a
TRISA bit (= 1) will make the corresponding PORTA pin an input (i.e., put the corresponding output driver in a Hi-
Impedance mode). Clearing a TRISA bit (= 0) will make the corresponding PORTA pin an output. Reading the
PORTA register reads the status of the pins, whereas writing to it will write to the port latch.
The RA4 pin is multiplexed with the Timer0 module clock input to become the RA4/T0CKI pin. The RA4/
T0CKI pin is a Schmitt Trigger input and an open drain output. The other PORTA pins are multiplexed with
analog inputs and the analog VREF+ and VREF- inputs. The operation of each pin is selected by clearing/setting
the control bits in the ADCON1 register (A/D Control Register1). The TRISA register controls the direction of the
RA pins, even when they are being used as analog inputs.

INITIALIZING PORTA:
Note: On a Power-on Reset, RA5 and RA3:RA0 are configured as analog inputs and read as ‘0’. RA6 and
RA4 are configured as digital inputs.
PORTA= 0; // Initialize PORTA by clearing output
ADCON1=0x07; //Configure A/D for digital inputs
TRISA=0XCF; //Set RA<3:0> as inputs RA<5:4> as outputs

PORTB AND TRISB REGISTERS:


PORTB is an 8-bit wide, bi-directional port. The corresponding Data Direction register is TRISB. Setting a
TRISB bit (= 1) will make the corresponding PORTB pin an input (i.e., put the corresponding output driver in a Hi-
Impedance mode). Clearing a TRISB bit (= 0) will
Make the corresponding PORTB pin an output (i.e., put the contents of the output latch on the selected pin).
Four of the PORTB pins, RB7:RB4, have an interrupt on- change feature. Only pins configured as inputs
can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is excluded from the interrupt
on- = change comparison).

INITIALIZING PORTB:
Note: On a Power-on Reset, these pins are configured as digital inputs.
PORTB=0; //Initialize PORTB by clearing output
TRISB=0XCF; //Set RB<3:0> as inputs RB<5:4> as outputs RB<7:6> as inputs
EMBEDDED SYSTEM DESIGN 58

PORTC AND TRISC REGISTERS:


PORTC is an 8-bit wide, bi-directional port. The corresponding Data Direction register is TRISC. Setting a
TRISC bit (= 1) will make the corresponding PORTC pin an input (i.e., put the corresponding output driver in a Hi-
Impedance mode).
Clearing a TRISC bit (= 0) will make the corresponding PORTC pin an output (i.e., put the contents of the
output latch on the selected pin). PORTC is multiplexed with several peripheral functions. When enabling
peripheral functions, care should be taken in defining TRIS bits for each PORTC pin. Some peripherals override
the TRIS bit to make a pin an output, while other peripherals override the TRIS bit to make a pin an input.
The user should refer to the corresponding peripheral section for the correct TRIS bit settings. The pin
override value is not loaded into the TRIS register.
INITIALIZING PORTC:
Note: On a Power-on Reset, these pins are configured as digital inputs.
PORTC=0; //Initialize PORTC by clearing output
TRISC=0XCF; //Set RC<3:0> as inputs RC<5:4> as outputs RC<7:6> as inputs

PORTD AND TRISD REGISTERS:


PORTD is an 8-bit wide, bi-directional port. The corresponding Data Direction register is TRISD. Setting a
TRISD bit (= 1) will make the corresponding PORTD pin an input (i.e., put the corresponding output driver in a
Hi-Impedance mode). Clearing a TRISD bit (= 0) will make the corresponding PORTD pin an output (i.e., put the
contents of the output latch on the selected pin).
PORTD is an 8-bit port with Schmitt Trigger input buffers. Each pin is individually configurable as an
input or output. PORTD can be configured as an 8-bit wide microprocessor port (parallel slave port) by setting
control bit PSPMODE (TRISE<4>). In this mode, the input buffers are TTL.
INITIALIZING PORTD:
Note: On a Power-on Reset, these pins are configured as digital inputs.
PORTD=0; //Initialize PORTD by clearing output
TRISD=0XCF; //Set RD<3:0> as inputs RD<5:4> as outputs RD<7:6> as inputs
PORTE AND TRISE REGISTERS:
PORTE is a 3-bit wide, bi-directional port. The corresponding Data Direction register is TRISE. Setting a
TRISE bit (= 1) will make the corresponding PORTE pin an input (i.e., put the corresponding output driver in a Hi-
Impedance mode). Clearing a TRISE bit (= 0) will make the corresponding PORTE pin an output.
PORTE has three pins (RE0/RD/AN5, RE1/WR/AN6 and RE2/CS/AN7) which are individually configurable
as inputs or outputs, which also controls the parallel slave port operation. PORTE pins are multiplexed with
analog inputs. TRISE controls the direction of the RE pins, even when they are being used as analog inputs.

INITIALIZING PORTE:
Note: On a Power-on Reset, these pins are configured as analog inputs.
PORTE=0; // Initialize PORTE by clearing output
ADCON1=0x07; //Configure A/D for digital inputs
TRISE=0X05; //Set Set RE<0>, RE<2> as inputs & RE<1> as output
EMBEDDED SYSTEM DESIGN 59
EMBEDDED SYSTEM DESIGN 60

UNIT 9: TIMERS IN PIC

TIMER0 MODULE:
The Timer0 module has the following features:
 Software selectable as an 8-bit or 16-bit timer/counter
 Readable and writable
 Dedicated 8-bit software programmable prescaler
 Clock source selectable to be external or internal
 Interrupt-on-overflow from FFh to 00h in 8-bit mode
 Interrupt-on-overflow from FFFFh to 0000h in 16-bit mode
 Edge select for external clock

The T0CON register is a readable and writable register that controls all the aspects of Timer0, including
the prescale selection.

BIT BI DESCRIPTION
NAME T
N
O
.
TMR0O 7 Timer0 On/Off Control bit:
N 1 = Enables Timer0
0 = Stops Timer0
T08BIT 6 Timer0 8-bit/16-bit Control bit:
1 = Timer0 is configured as an 8-bit timer/counter
0 = Timer0 is configured as a 16-bit timer/counter
T0CS 5 Timer0 Clock Source Select bit:
1 = Transition on T0CKI pin
0 = Internal instruction cycle clock (CLKO)
T0SE 4 Timer0 Source Edge Select bit:
1 = high-to-low transition on T0CKI pin
0 = low-to-high transition on T0CKI pin
3 Timer0 Prescaler Assignment bit:
PSA 1 = Timer0 prescaler is NOT assigned. Timer0 clock input bypasses
prescaler.
0 = Timer0 prescaler is assigned. Timer0 clock input comes
from prescaler output.

T0PS2:T 2- Timer0 Prescaler Select bits


EMBEDDED SYSTEM DESIGN 61

0PS0 0

TIMER0 OPERATION:
Timer0 can operate as a timer or as a counter. Timer mode is selected by clearing the T0CS bit. In Timer
mode, the Timer0 module will increment every instruction cycle (without prescaler). If the TMR0L register is
written, the increment is inhibited for the following
two instruction cycles. The user can work around this by writing an adjusted value to the TMR0L register.
Counter mode is selected by setting the T0CS bit.
In Counter mode, Timer0 will increment, either on every rising or falling edge of pin RA4/T0CKI. The
incrementing edge is determined by the Timer0 Source Edge Select bit (T0SE). Clearing the T0SE bit selects the
rising edge. Restrictions on the external clock input are discussed below.
When an external clock input is used for Timer0, it must meet certain requirements. The requirements
ensure the external clock can be synchronized with the internal phase clock (TOSC).
PRESCALER:
An 8-bit counter is available as a prescaler for the Timer0 module. The prescaler is not readable or
writable.The PSA and T0PS2:T0PS0 bits determine the prescaler assignment and prescale ratio. Clearing bit PSA
EMBEDDED SYSTEM DESIGN 62

will assign the prescaler to the Timer0 module. When the prescaler is assigned to the Timer0 module, prescale
values of 1:2, 1:4,..., 1:256 are selectable.

TIMER0 INTERRUPT:
The TMR0 interrupt is generated when the TMR0 register overflows from FFh to 00h in 8-bit mode, or
FFFFh to 0000h in 16-bit mode. This overflow sets the TMR0IF bit. The interrupt can be masked by clearing the
TMR0IE bit. The TMR0IE bit must be cleared in software by the Timer0 module Interrupt Service Routine before
re-enabling this interrupt.

STEPS TO PROGRAM TIMER 0:


1. Load the T0CON value
2. Load initial counting value to TMR0H and TMR0L
3. Start the timer (TMR0ON=1)
4. Keep monitoring the timer flag (TMR0IF)
5. If ‘1’ stop the timer (TMR0ON=0)
6. Clear the TMR0IF flag
7. Go back to step 2

EXAMPLE: GENERATE A SQUAREWAVE ON RC0 OF USING TIMER0, WITHOUT PRESCALER.

#include<P18F4520.h>
void main()
{
TRISCbits.TRISC0=0;
T0CON=0X08;
while(1)
{
TMR0H=0;
TMR0L=0;
T0CONbits.TMR0ON=1;
while(INTCONbits.TMR0IF==0);
PORTCbits.RC0=~ PORTCbits.RC0;
T0CONbits.TMR0ON=0;
INTCONbits.TMR0IF=0 ;
EMBEDDED SYSTEM DESIGN 63

}
}

TIMER1 MODULE:
The Timer1 module timer/counter has the following features:
 16-bit timer/counter (two 8-bit registers; TMR1H and TMR1L)
 Readable and writable (both registers)
 Internal or external clock select
 Interrupt-on-overflow from FFFFh to 0000h
 RESET from CCP module special event trigger
Timer1 control register (T1CON) controls the Operating mode of the Timer1module, and contains the
Timer1 oscillator enable bit(T1OSCEN). Timer1 can be enabled or disabled by setting or clearing control bit
TMR1ON (T1CON<0>).

BIT NAME BIT DESCRIPTION


NO.
RD16 7 16-bit Read/Write Mode Enable bit:
1 = Enables register Read/Write of Timer1 in one 16-bit operation
0 = Enables register Read/Write of Timer1 in two 8-bit operations
- 6 Unimplemented:
Read as '0'
T1CKPS1:T1CKPS 5-4 Timer1 Input Clock Prescale Select bits
0
T1OSCEN 3 Timer1 Oscillator Enable bit:
1 = Timer1 Oscillator is enabled
0 = Timer1 Oscillator is shut-off
T1SYNC 2 Timer1 External Clock Input Synchronization Select bit:
When TMR1CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR1CS = 0:
This bit is ignored. Timer1 uses the internal clock when
TMR1CS = 0.
TMR1CS 1 Timer1 Clock Source Select bit:
1 = External clock from pin RC0/T1OSO/T13CKI
EMBEDDED SYSTEM DESIGN 64

(on the rising edge)


0 = Internal clock (FOSC/4)
TMR1ON Timer1 On bit:
0 1 = Enables Timer1
0 = Stops Timer1

TIMER1 OPERATION:
Timer1 can operate in one of these modes:
 As a timer
 As a synchronous counter
 As an asynchronous counter
The Operating mode is determined by the clock select bit, TMR1CS (T1CON<1>). When TMR1CS = 0,
Timer1 increments every instruction cycle. When TMR1CS = 1, Timer1 increments on every rising edge of the
external clock input or the Timer1 oscillator, if enabled.
When the Timer1 oscillator is enabled (T1OSCEN is set), the RC1/T1OSI and RC0/T1OSO/T1CKI pins
become inputs. That is, the TRISC<1:0> value is ignored, and the pins are read as ‘0’. Timer1 also has an internal
“RESET input”. This RESET can be generated by the CCP module.

TIMER1 INTERRUPT:
The TMR1 Register pair (TMR1H:TMR1L) increments from 0000h to FFFFh and rolls over to 0000h. The
TMR1 Interrupt, if enabled, is generated on overflow, which is latched in interrupt flag bit TMR1IF (PIR1<0>).
This interrupt can be enabled/disabled by setting/ clearing TMR1 interrupt enable bit, TMR1IE (PIE1<0>).
EMBEDDED SYSTEM DESIGN 65

TIMER2 MODULE :
The Timer2 module timer has the following features:
 8-bit timer (TMR2 register)
 8-bit period register (PR2)
 Readable and writable (both registers)
 Software programmable prescaler (1:1, 1:4, 1:16)
 Software programmable postscaler (1:1 to 1:16)
 Interrupt on TMR2 match of PR2
 SSP module optional use of TMR2 output to
 generate clock shift

Timer2 has a control register .Timer2 can be shut-off by clearing control bit TMR2ON (T2CON<2>) to
minimize power consumption. Figure 12-1 is a simplified block diagram of the Timer2module. Register 12-1
shows the Timer2 control register. The prescaler and postscale r selection of Timer2 are controlled by this
register.

TIMER2 OPERATION:
Timer2 can be used as the PWM time-base for the PWM mode of the CCP module. The TMR2 register is
readable and writable, and is cleared on any device RESET. The input clock (FOSC/4) has a prescale option of
1:1, 1:4 or 1:16, selected by control bits T2CKPS1:T2CKPS0 (T2CON<1:0>). The match output of TMR2 goes
EMBEDDED SYSTEM DESIGN 66

through a 4-bit postscaler (which gives a 1:1 to 1:16 scaling inclusive) to generate a TMR2 interrupt (latched in
flag bit TMR2IF,(PIR1<1>)).
The prescaler and postscaler counters are cleared when any of the following occurs:
 a write to the TMR2 register
 a write to the T2CON register
 any device RESET

BIT NAME BIT DESCRIPTION


NO.
- 7 Unimplemented: Read as '0'
TOUTPS3:TOUTPS0 6-3 Timer2 Output Postscale Select bits:
0000 = 1:1 Postscale
0001 = 1:2 Postscale


1111 = 1:16 Postscale
TMR2ON 2 Timer2 On bit:
1 = Timer2 is on
0 = Timer2 is off
T2CKPS1:T2CKPS0 1-0 Timer2 Clock Prescale Select bits:
00 = Prescaler is 1
01 = Prescaler is 4
1x = Prescaler is 16

TIMER2 INTERRUPT:
The Timer2 module has an 8-bit period register, PR2. Timer2 increments from 00h until it match PR2
and then resets to 00h on the next increment cycle. PR2 is a readable and writable register. The PR2 register is
initialized to FFh upon RESET.
EMBEDDED SYSTEM DESIGN 67

TIMER3 MODULE:
The Timer3 module timer/counter has the following features:
 16-bit timer/counter (two 8-bit registers; TMR3H and TMR3L)
 Readable and writable (both registers)
 Internal or external clock select
 Interrupt-on-overflow from FFFFh to 0000h
 RESET from CCP module trigger
Timer3 control register controls the Operating mode of the Timer3 module and sets the CCP clock
source.This register controls the Operating mode of the Timer1 module, as well as contains the Timer1
oscillator enable bit (T1OSCEN), which can be a clock source for Timer3.

BIT NAME B DESCRIPTION


I
T
N
O
.
RD16 7 16-bit Read/Write Mode Enable bit:
1 = Enables register Read/Write of Timer3 in one 16-bit operation
0 = Enables register Read/Write of Timer3 in two 8-bit operations
T3CCP2:T3CC 6 Timer3 and Timer1 to CCPx Enable bits:
P1 - 1x = Timer3 is the clock source for compare/capture CCP modules
3 01 = Timer3 is the clock source for compare/capture of CCP2,
Timer1 is the clock source for compare/capture of CCP1
00 = Timer1 is the clock source for compare/capture CCP modules
EMBEDDED SYSTEM DESIGN 68

T3CKPS1:T3C 5 Timer3 Input Clock Prescale Select bits:


KPS0 - 11 = 1:8 Prescale value
4 10 = 1:4 Prescale value
01 = 1:2 Prescale value
00 = 1:1 Prescale value

T3SYNC 2 Timer3 External Clock Input Synchronization Control bit:


When TMR3CS = 1:
1 = Do not synchronize external clock input
0 = Synchronize external clock input
When TMR3CS = 0:
This bit is ignored. Timer3 uses the internal clock when TMR3CS = 0.

TMR3CS 1 Timer3 Clock Source Select bit:


1 = External clock input from Timer1 oscillator or T1CKI
0 = Internal clock (FOSC/4)
TMR3ON 1 Timer3 On bit:
1 = Enables Timer3
0 = Stops Timer3

TIMER3 OPERATION:
Timer3 can operate in one of these modes:
 As a timer
 As a synchronous counter
 As an asynchronous counter
The Operating mode is determined by the clock select bit, TMR3CS (T3CON<1>).
When TMR3CS = 0, Timer3 increments every instruction cycle. When TMR3CS = 1, Timer3 increments on every
rising edge of the Timer1 external clock input or the Timer1 oscillator, if enabled. When the Timer1 oscillator is
enabled (T1OSCEN is set), the RC1/T1OSI and RC0/T1OSO/T1CKI pins become inputs.
EMBEDDED SYSTEM DESIGN 69

TIMER3 INTERRUPT:
The TMR3 Register pair (TMR3H:TMR3L) increments from 0000h to FFFFh and rolls over to 0000h. The
TMR3 Interrupt, if enabled, is generated on overflow, which is latched in interrupt flag bit, TMR3IF (PIR2<1>).
This interrupt can be enabled/disabled by setting/clearing TMR3 interrupt enable bit, TMR3IE (PIE2<1>).

UNIT 10: ADDRESSABLE USART


The Universal Synchronous Asynchronous Receiver Transmitter (USART) module is one of the two serial
I/O modules. (USART is also known as a Serial Communications Interface or SCI.) The USART can be configured
as a full duplex asynchronous system that can communicate with peripheral devices, such as CRT terminals and
personal computers, or it can be configured as a half-duplex synchronous system that can communicate with
peripheral devices, such as A/D or D/A integrated circuits, serial EEPROMs, etc.
The USART can be configured in the following modes:
 Asynchronous (full-duplex)
 Synchronous - Master (half-duplex)
 Synchronous - Slave (half-duplex)
In order to configure pins RC6/TX/CK and RC7/RX/DT as the Universal Synchronous Asynchronous
Receiver Transmitter:
 bit SPEN (RCSTA<7>) must be set (= 1),
 bit TRISC<6> must be cleared (= 0), and
 bit TRISC<7> must be set (=1).

BIT BIT DESCRIPTION


NAME NO
.
EMBEDDED SYSTEM DESIGN 70

CSRC 7 Clock Source Select bit:


1 = Master mode (clock generated internally from BRG)
0 = Slave mode (clock from external source)
TX9 6 9-bit Transmit Enable bit:
1 = Selects 9-bit transmission
0 = Selects 8-bit transmission
TXEN 5 Transmit Enable bit:
1 = Transmit enabled
0 = Transmit disabled
SYNC 4 USART Mode Select bit:
1 = Synchronous mode
0 = Asynchronous mode
3 Unimplemented:
- Read as '0'
High Baud Rate Select bit:
BRGH 2 Asynchronous mode:
1 = High speed
0 = Low speed
Synchronous mode:
Unused in this mode
Transmit Shift Register Status bit:
TRMT 1 1 = TSR empty
0 = TSR full
9th bit of Transmit Data:
TX9D 0 Can be Address/Data bit or a parity bit.

BIT DESCRIPTION
NA
ME

SPE Serial Port Enable bit:


N 1 = Serial port enabled (configures RX/DT and TX/CK pins as serial port pins)
0 = Serial port disabled
RX9 9-bit Receive Enable bit:
1 = Selects 9-bit reception
0 = Selects 8-bit reception
SRE Single Receive Enable bit:
EMBEDDED SYSTEM DESIGN 71

N Asynchronous mode:
Don’t care
Synchronous mode - Master:
1 = Enables single receive
0 = Disables single receive
This bit is cleared after reception is complete.
Synchronous mode - Slave:
Don’t care
CRE Continuous Receive Enable bit:
N Asynchronous mode:
1 = Enables receiver
0 = Disables receiver
Synchronous mode:
1 = Enables continuous receive until enable bit CREN is cleared
(CREN overrides SREN)
0 = Disables continuous receive
Address Detect Enable bit:
ADD Asynchronous mode 9-bit (RX9 = 1):
EN 1 = Enables address detection, enable interrupt and load of the receive buffer
when RSR<8> is set
0 = Disables address detection, all bytes are received, and ninth bit can be
used as parity bit
Framing Error bit:
FER 1 = Framing error (can be updated by reading RCREG register and receive next
R valid byte)
0 = No framing error
Overrun Error bit:
OER 1 = Overrun error (can be cleared by clearing bit CREN)
R 0 = No overrun error
9th bit of Received Data:
RX9 This can be Address/Data bit or a parity bit, and must be calculated by user
D firmware.

USART BAUD RATE GENERATOR (SPBRG):


The BRG supports both the Asynchronous and Synchronous modes of the USART. It is a dedicated 8-bit
baud rate generator. The SPBRG register controls the period of a free running 8-bit timer. In Asynchronous
mode, bit BRGH (TXSTA<2>) also controls the baud rate. In Synchronous mode, bit BRGH is ignored.
EMBEDDED SYSTEM DESIGN 72

USART ASYNCHRONOUS MODE:


In this mode, the USART uses standard non-return-to zero (NRZ) format (one START bit, eight or nine
data bits and one STOP bit). The most common data format is 8-bits. An on-chip dedicated 8-bit baud rate
generator can be used to derive standard baud rate frequencies from the oscillator. The USART transmits and
receives the LSB first. The baud rate generator produces a clock, either x16 or x64 of the bit shift rate,
depending on bit BRGH (TXSTA<2>). Asynchronous mode is selected by clearing bit SYNC (TXSTA<4>). The
USART Asynchronous module consists of the following important elements:
 Baud Rate Generator
 Sampling Circuit
 Asynchronous Transmitter
 Asynchronous Receiver

USART ASYNCHRONOUS TRANSMITTER:


The heart of the transmitter is the Transmit (serial) Shift Register (TSR). The shift register obtains its data
from the read/write transmit buffer, TXREG. The TXREG register is loaded with data in software. The TSR
EMBEDDED SYSTEM DESIGN 73

register is not loaded until the STOP bit has been transmitted from the previous load. As soon as the STOP bit is
transmitted, the TSR is loaded with new data from the TXREG register (if available).
Once the TXREG register transfers the data to the TSR register the TXREG register is empty and flag bit
TXIF (PIR1<4>) is set. This interrupt can be enabled/disabled by setting/clearing enable bit TXIE ( PIE1<4>). Flag
bit TXIF will be set, regardless of the state of enable bit TXIE and cannot be cleared in software. It will reset only
when new data is loaded into the TXREG register.
While flag bit TXIF indicated the status of the TXREG register, another bit, TRMT (TXSTA<1>), shows the
status of the TSR register. Status bit TRMT is a read-only bit, which is set when the TSR register is empty

USART ASYNCHRONOUS RECEIVER:


EMBEDDED SYSTEM DESIGN 74

The data is received on the RC7/RX/DT pin and drives the data recovery block. The data recovery block
is actually a high speed shifter operating at x16 times the baud rate, whereas the main receive serial shifter
operates at the bit rate or at FOSC. This mode would
typically be used in RS-232 systems.

TRANSMIT PROGRAM:
STEPS TO TRANSMIT TO THE VIRTUAL TERMINAL:
1. Load the TXSTA value
2. Load the SPBRG value
3. Enable the SPEN pin of RCSTA
4. Load the value to be transmitted to the TXREG register
5. Keep monitoring the transmit flag (TXIF)
6. If ‘1’ clear the TXIF flag
7. Go back to step 5
EXAMPLE: PROGRAM TO TRANSMIT ‘A’ TO THE VIRTUAL TERMINAL, XTAL=16MHz
#include<P18F4520.h>
void main()
{
TXSTA=0X20;
SPBRG=25;
RCSTA=0X80;
EMBEDDED SYSTEM DESIGN 75

while(1)
{
TXREG=’A’;
while(PIR1bits.TXIF==0);
PIR1bits.TXIF=0;
}
}
RECEIVE PROGRAM:
STEPS TO RECEIVE FROM THE VIRTUAL TERMINAL:
1.Load the RCSTA value
2.Load the SPBRG value
3. Keep monitoring the transmit flag (RCIF)
6. If ‘1’ store the received value in a location
7. Clear the RCIF flag
8. Go back to step 3
EXAMPLE: PROGRAM TO RECEIVE FROM THE VIRTUAL TERMINAL AND STORE TO IN PORTB, XTAL=16MHz

#include<P18F4520.h>
void main()
{
TRISB=0;
SPBRG=25;
RCSTA=0X90;
while(1)
{
while(PIR1bits.RCIF==0);
PORTB=RCREG;
PIR1bits.RCIF=0; } }

UNIT 11: INTERRUPTS

The PIC18FXX2 devices have multiple interrupt sources and an interrupt priority feature that allows
each interrupt source to be assigned a high priority level or a low priority level. The high priority interrupt
vector is at 000008h and the low priority interrupt vector is at 000018h.
High priority interrupt events will override any low priority interrupts that may be in progress. There are
ten registers which are used to control interrupt operation. These registers are:
 RCON
 INTCON
 INTCON2
 INTCON3
 PIR1, PIR2
 PIE1, PIE2
 IPR1, IPR2
EMBEDDED SYSTEM DESIGN 76

Each interrupt source, except INT0, has three bits to control its operation, these bits are:
 Flag bit to indicate that an interrupt event occurred
 Enable bit that allows program execution to branch to the interrupt vector address when the flag bit is set
 Priority bit to select high priority or low priority

The interrupt priority feature is enabled by setting the IPEN bit (RCON<7>). When interrupt priority is
enabled, there are two bits which enable interrupts globally.
 Setting the GIEH bit (INTCON<7>) enables all interrupts that have the priority bit set.
 Setting the GIEL bit (INTCON<6>) enables all interrupts that have the priority bit cleared.

When the interrupt flag, enable bit and appropriate global interrupt enable bit are set, the interrupt will vector
immediately to address 000008h or 000018h, depending on the priority level. When the IPEN bit is cleared (default
state), the interrupt priority feature is disabled.
In Compatibility mode, the interrupt priority bits for each source have no effect. INTCON<6> is the PEIE bit, which
enables/disables all peripheral interrupt sources. INTCON<7> is the GIE bit, which enables/disables all interrupt
sources. All interrupts branch to address 000008h in Compatibility mode. When an interrupt is responded to, the
Global Interrupt Enable bit is cleared to disable further interrupts.
If the IPEN bit is cleared, this is the GIE bit. If interrupt priority levels are used, this will be either the GIEH or GIEL
bit. High priority interrupt sources can interrupt a low priority interrupt.
The return address is pushed onto the stack and the PC is loaded with the interrupt vector address (000008h or
000018h). The “return from interrupt” instruction, RETFIE, exits the interrupt routine and sets the GIE bit (GIEH or GIEL
if priority levels are used), which re-enables interrupts.
EMBEDDED SYSTEM DESIGN 77

INTCON REGISTERS:
EMBEDDED SYSTEM DESIGN 78

The INTCON Registers are readable and writable registers, which contain various enable, priority and
flag bits.

BIT NAME BIT NO. DESCRIPTION


GIE/GIEH 7 Global Interrupt Enable bit:
1 = Enables all unmasked interrupts
0 = Disables all interrupts
PEIE/GIEL 6 Peripheral Interrupt Enable bit:
1 = Enables all unmasked peripheral interrupts
0 = Disables all peripheral interrupts
TMR0IE 5 TMR0 Overflow Interrupt Enable bit:
1 = Enables the TMR0 overflow interrupt
0 = Disables the TMR0 overflow interrupt
INT0IE 4 INT0 External Interrupt Enable bit:
1 = Enables the INT0 external interrupt
0 = Disables the INT0 external interrupt
RBIE 3 RB Port Change Interrupt Enable bit:
1 = Enables the RB port change interrupt
0 = Disables the RB port change interrupt
TMR0IF 2 TMR0 Overflow Interrupt Flag bit:
BIT NAME BIT NO. DESCRIPTION
1 = TMR0 register has overflowed
RBPU 7 PORTB
(must Pull-up Enable
be cleared bit:
in software)
0 =1 TMR0
= All PORTB pull-ups
register did notare disabled
overflow
INT0IF 1 INT0 External Interrupt Flag bit: by individual
0 = PORTB pull-ups are enabled
1 =port
Thelatch
INT0values
external interrupt occurred
(must be cleared in software)
INTEDG0 6 0 =External
The INT0Interrupt0 Edge Select
external interrupt didbit:
not occur
1 = Interrupt on rising edge
RBIF 0 RB0Port Changeon
= Interrupt Interrupt Flag bit:
falling edge
1 = At least one of the RB7-RB4 pins changed state
INTEDG1 5 (must be cleared
External in software)
Interrupt1 Edge Select bit:
0 =1 None of theon
= Interrupt RB7-RB4 pins have changed state
rising edge
0 = Interrupt on falling edge

INTEDG2 4 External Interrupt2 Edge Select bit:


1 = Interrupt on rising edge
0 = Interrupt on falling edge
EMBEDDED SYSTEM DESIGN 79

- 3 Unimplemented:
Read as '0'

TMR0IP 2 TMR0 Overflow Interrupt Priority bit:


1 = High priority
0 = Low priority

- 1 Unimplemented:
Read as '0'

RBIP 0 RB Port Change Interrupt Priority bit:


1 = High priority
0 = Low priority

BIT NAME BIT NO. DESCRIPTION


INT2IP 7 INT2 External Interrupt Priority bit:
1 = High priority
0 = Low priority
INT1IP 6 INT1 External Interrupt Priority bit:
1 = High priority
0 = Low priority
- 5 Unimplemented:
Read as '0'
INT2IE 4 INT2 External Interrupt Enable bit:
1 = Enables the INT2 external interrupt
0 = Disables the INT2 external interrupt
INT1IE 3 INT1 External Interrupt Enable bit:
1 = Enables the INT1 external interrupt
0 = Disables the INT1 external interrupt
- 2 Unimplemented:
Read as '0’
EMBEDDED SYSTEM DESIGN 80

INT2IF 1 INT2 External Interrupt Flag bit:


1 = The INT2 external interrupt occurred
(must be cleared in software)
0 = The INT2 external interrupt did not occur
INT1IF 0 INT1 External Interrupt Flag bit:
1 = The INT1 external interrupt occurred
(must be cleared in software)
0 = The INT1 external interrupt did not occur

PIR REGISTERS:
The PIR registers contain the individual flag bits for the peripheral interrupts. Due to the number of
peripheral interrupt sources, there are two Peripheral Interrupt Flag Registers (PIR1, PIR2).

BIT BI DESCRIPTION
NAM T
E N
O
.
PSPIF 7 Parallel Slave Port Read/Write Interrupt Flag bit:
1 = A read or a write operation has taken place (must be cleared in
software)
0 = No read or write has occurred
ADIF 6 A/D Converter Interrupt Flag bit:
1 = An A/D conversion completed (must be cleared in software)
0 = The A/D conversion is not complete
RCIF 5 USART Receive Interrupt Flag bit:
1 = The USART receive buffer, RCREG, is full (cleared when RCREG
is read)
0 = The USART receive buffer is empty
TXIF 4 USART Transmit Interrupt Flag bit :
EMBEDDED SYSTEM DESIGN 81

1 = The USART transmit buffer, TXREG, is empty (cleared when


TXREG is written)
0 = The USART transmit buffer is full
SSPIF 3 Master Synchronous Serial Port Interrupt Flag bit:
1 = The transmission/reception is complete (must be cleared in
software)
0 = Waiting to transmit/receive
CCP1I 2 CCP1 Interrupt Flag bit:
F Capture mode:
1 = A TMR1 register capture occurred (must be cleared in
software)
0 = No TMR1 register capture occurred
Compare mode:
1 = TMR1 register compare match occurred (must be cleared in
software)
0 = No TMR1 register compare match occurred
PWM mode: Unused in this mode
TMR2 1 TMR2 to PR2 Match Interrupt Flag bit:
IF 1 = TMR2 to PR2 match occurred (must be cleared in software)
0 = No TMR2 to PR2 match occurred
TMR1 0 TMR1 Overflow Interrupt Flag bit:
IF 1 = TMR1 register overflowed (must be cleared in software)
0 =TMR1 register did not overflow

BIT BI DESCRIPTION
NAM T
E N
O
.
- 7- Unimplemented:
5 Read as '0'
EEIF 4 Data EEPROM/FLASH Write Operation Interrupt Flag bit:
1 = The Write operation is complete (must be cleared in software)
0 = The Write operation is not complete, or has not been started
BCLIF 3 Bus Collision Interrupt Flag bit:
1 = A bus collision occurred (must be cleared in software)
0 = No bus collision occurred
EMBEDDED SYSTEM DESIGN 82

LVDIF 2 Low Voltage Detect Interrupt Flag bit:


1 = A low voltage condition occurred (must be cleared in software)
0 = The device voltage is above the Low Voltage Detect trip point
TMR3 1 TMR3 Overflow Interrupt Flag bit:
IF 1 = TMR3 register overflowed (must be cleared in software)
0 = TMR3 register did not overflow
CCP2I 0 CCPx Interrupt Flag bit:
F Capture mode:
1 = A TMR1 register capture occurred (must be cleared in software)
0 = No TMR1 register capture occurred
Compare mode:
1 = A TMR1 register compare match occurred (must be cleared in software)
0 = No TMR1 register compare match occurred
PWM mode: Unused in this mode

PIE REGISTERS:
The PIE registers contain the individual enable bits for the peripheral interrupts. Due to the number of
peripheral interrupt sources, there are two Peripheral Interrupt Enable Registers (PIE1, PIE2). When IPEN = 0,
the PEIE bit must be set to enable any of these peripheral interrupts.

BIT BIT DESCRIPTION


NAM NO.
E
PSPIE 7 Parallel Slave Port Read/Write Interrupt Enable bit:
1 = Enables the PSP read/write interrupt
0 = Disables the PSP read/write interrupt
ADIE 6 A/D Converter Interrupt Enable bit:
1 = Enables the A/D interrupt
0 = Disables the A/D interrupt
EMBEDDED SYSTEM DESIGN 83

RCIE 5 USART Receive Interrupt Enable bit:


1 = Enables the USART receive interrupt
0 = Disables the USART receive interrupt
TXIE 4 USART Transmit Interrupt Enable bit:
1 = Enables the USART transmit interrupt
0 = Disables the USART transmit interrupt
SSPIE 3 Master Synchronous Serial Port Interrupt Enable bit:
1 = Enables the MSSP interrupt
0 = Disables the MSSP interrupt
CCP1I 2 CCP1 Interrupt Enable bit:
E 1 = Enables the CCP1 interrupt
0 = Disables the CCP1 interrupt
TMR2 1 TMR2 to PR2 Match Interrupt Enable bit:
IE 1 = Enables the TMR2 to PR2 match interrupt
0 = Disables the TMR2 to PR2 match interrupt
TMR1 0 TMR1 Overflow Interrupt Enable bit:
IE 1 = Enables the TMR1 overflow interrupt
0 = Disables the TMR1 overflow interrupt

BIT BI DESCRIPTION
NA T
ME N
O
.
- 7- Unimplemented:
5 Read as '0'
EEIE 4 Data EEPROM/FLASH Write Operation Interrupt Enable bit:
1 = Enabled
0 = Disabled
BCLI 3 Bus Collision Interrupt Enable bit:
E 1 = Enabled
0 = Disabled
LVDI 2 Low Voltage Detect Interrupt Enable bit:
E 1 = Enabled
0 = Disabled
TMR 1 TMR3 Overflow Interrupt Enable bit:
3IE
EMBEDDED SYSTEM DESIGN 84

1 = Enables the TMR3 overflow interrupt


0 = Disables the TMR3 overflow interrupt
CCP2 0 CCP2 Interrupt Enable bit:
IE 1 = Enables the CCP2 interrupt
0 = Disables the CCP2 interrupt

IPR REGISTERS:
The IPR registers contain the individual priority bits for the peripheral interrupts. Due to the number of
peripheral interrupt sources, there are two Peripheral Interrupt Priority Registers (IPR1, IPR2). The operation of
the priority bits requires that the Interrupt Priority Enable (IPEN) bit be set.

BIT NAME BIT NO. DESCRIPTION


PSPIP 7 Parallel Slave Port Read/Write Interrupt Priority bit:
1 = High priority
0 = Low priority
ADIP 6 A/D Converter Interrupt Priority bit:
1 = High priority
0 = Low priority
RCIP 5 USART Receive Interrupt Priority bit:
1 = High priority
0 = Low priority
EMBEDDED SYSTEM DESIGN 85

TXIP 4 USART Transmit Interrupt Priority bit:


1 = High priority
0 = Low priority
SSPIP 3 Master Synchronous Serial Port Interrupt Priority bit:
1 = High priority
0 = Low priority
CCP1IP 2 CCP1 Interrupt Priority bit:
1 = High priority
0 = Low priority
TMR2IP 1 TMR2 to PR2 Match Interrupt Priority bit:
1 = High priority
0 = Low priority
TMR1IP 0 TMR1 Overflow Interrupt Priority bit:
1 = High priority
0 = Low priority

BIT BIT DESCRIPTION


NAME NO.
- 7-5 Unimplemented:
Read as '0'
EEIP 4 Data EEPROM/FLASH Write Operation Interrupt Priority bit:
1 = High priority
0 = Low priority
BCLIP 3 Bus Collision Interrupt Priority bit:
1 = High priority
0 = Low priority
LVDIP 2 Low Voltage Detect Interrupt Priority bit:
1 = High priority
0 = Low priority
TMR3IP 1 TMR3 Overflow Interrupt Priority bit:
1 = High priority
0 = Low priority
CCP2IP 0 CCP2 Interrupt Priority bit:
1 = High priority
0 = Low priority
EMBEDDED SYSTEM DESIGN 86

INT0 INTERRUPT:
External interrupts on the RB0/INT0, RB1/INT1 and RB2/INT2 pins are edge triggered: either rising, if
the corresponding INTEDGx bit is set in the INTCON2 register,
or falling, if the INTEDGx bit is clear. When a valid edge appears on the RBx/INTx pin, the corresponding flag bit
INTxF is set. This interrupt can be disabled by clearing the corresponding enable bit INTxE. Flag bit INTxF must
be cleared in software in the Interrupt Service Routine before re-enabling the interrupt.
All external interrupts (INT0, INT1 and INT2) can wake-up the processor from SLEEP, if bit INTxE was set
prior to going into SLEEP. If the global interrupt enable bit GIE is set, the processor will branch to the interrupt
vector following wake-up. Interrupt priority for INT1 and INT2 is determined by the value contained in the
interrupt priority bits, INT1IP (INTCON3<6>) and INT2IP (INTCON3<7>). There is no priority bit associated with
INT0. It is always a high priority interrupt source.

TMR0 INTERRUPT:
In 8-bit mode (which is the default), an overflow (FFh -> 00h) in the TMR0 register will set flag bit
TMR0IF. In 16-bit mode, an overflow (FFFFh ->0000h) in the TMR0H, TMR0L registers will set flag bit
TMR0IF.The interrupt can be enabled/disabled by setting/ clearing enable bit T0IE (INTCON<5>). Interrupt
priority for Timer0 is determined by the value contained in the interrupt priority bit TMR0IP (INTCON2<2>).
PORTB INTERRUPT-ON-CHANGE:
An input change on PORTB<7:4> sets flag bit RBIF (INTCON<0>). The interrupt can be enabled/disabled
by setting/clearing enable bit, RBIE (INTCON<3>). Interrupt priority for PORTB interrupt-on-change is
determined by the value contained in the interrupt priority bit, RBIP (INTCON2<0>).

INTERRUPT PROGRAMMING:
EXAMPLE: PROGRAM TO TOGGLE RB1 USING TIMER0 AND SIMULTANEOUSLY MOVE THE VALUE FROM
PORTC TO PORTD

#include<P18F4520.h>
#define x PORTBbits.RB1
#pragma code main=0x200
#pragma interrupt timer0int void main()
void timer0int() {
{ TRISBbits.TRISB1=0;
x=~x; TRISC=0XFF;
TMR0H=0; TRISD=0;
TMR0L=0; T0CON=0X08;
INTCONbits.TMR0IF=0; TMR0H=0;
} TMR0L=0;
INTCONbits,TMR0IE=1;
#pragma code timer0=0x08 INTCONbits.GIE=1;
void timer0() T0CONbits.TMR0ON=1;
{ while(1)
timer0int(); {
} PORTD=PORTC;
EMBEDDED SYSTEM DESIGN 87

}
EMBEDDED SYSTEM DESIGN 88

EXAMPLE: WAP TO GENERATE A SQUARE WAVE ON RB1 & RB5 USING T0 &T1 AND TRANSFER DATA FROM PORTD
TO PORTC . ASSIGN T0 AS HIGH PRIORITY.

#include<P18F4520.H>
#define x PORTBbits.RB1
#define y PORTBbits.RB7

#pragma interrupt timer0int


void timer0int()
{
x=~x;
TMR0H=0;
TMR0L=0;
INTCONbits.TMR0IF=0;
}

#pragma interrupt timer1int


void timer1int()
{
y=~y;
TMR1H=0;
TMR1L=0;
PIR1bits.TMR1IF=0;
}

#pragma code timer0=0x08


void timer0()
{
timer0int();
}

#pragma code timer1=0x18


void timer1()
{
timer1int();
}

#pragma code main=0x200


void main()
{
TRISBbits.TRISB1=0;
TRISBbits.TRISB7=0;
TRISC=0XFF;
EMBEDDED SYSTEM DESIGN 89

TRISD=0;
T0CON=0X08;
T1CON=0;
TMR0H=0;
TMR0L=0;
TMR1H=0;
TMR1L=0;
INTCONbits,TMR0IE=1;
PIE1bits.TMR1IE=1;
INTCONbits.GIE=1;
INTCONbits.PEIE=1;
T0CONbits.TMR0ON=1;
T1CONbits.TMR1ON=1;
RCONbits.IPEN=1;
IPR1bits.TMR1IP=0;
INTCON2bits.TMR0IP=1;
while(1)
{
PORTD=PORTC;
}
}
EMBEDDED SYSTEM DESIGN 90

LIST OF INSTRUCTIONS (FOR ASSEMBLY PROGRAMMING):

Data Transfer Instructions:-


 MOVLW K :Move constant to W
 MOVWF f :Move W to f
 MOVF f, d :Move f to
 CLRF f :Clear f
 SETF f :Set f
 SWAPF f, d :Swap nibbles in f
 MOVFF f1,f2 :Move filereg1 to filereg2

Arithmetic-logic Instructions :-
 ADDLW k : Add W and constant
 ADDWF f,d : Add W and f
 SUBLW k : Subtract W from constant k
 SUBWF f,d :Subtract W from f
 SUBFWB f,d : Subtract f from W with borrow
 ANDLW k : Logical AND with W with constant
 ANDWF f,d : Logical AND with W with f
 ANDWF f,d : Logical AND with W with f
 IORLW k : Logical OR with W with constant W
 IORWF f,d : Logical OR with W with f
 XORLW k : Logical XOR with W with constant
 XORWF f,d : Logical XOR with W with f
 INCF f,d :Increment f by 1
 INCFSZ f,d : Increment f by 1 and skip if zero
 INCFSNZ f,d : Increment f by 1 and skip if not zero
 DECF f,d :Decrement f by 1
 DECFSZ f,d :Decrement f by 1 and skip if zero
 DECFSNZ f,d : Decrement f by 1 and skip if not zero
 RLF f,d :Rotate left f through CARRY bit C
 RRF f,d :Rotate right f through CARRY bit C
 COMF f,d : Complement f

Bit-oriented Instructions:-
 BCF f,b :Clear bit b in f
 BSF f,b : Set bit b in f
 BTG f,b :bit toggle in f
 BTFSC f,b :Test bit b of f. Skip if clear
 BTFSS f,b :Test bit b of f. Skip if set

Program Control Instructions:-


EMBEDDED SYSTEM DESIGN 91

 GOTO k : Go to address k
 CALL k : Call subroutine
 RETURN : Return from subroutine
 RETFIE :Return from interrupt
 NOP :No operation
 CLRWDT :Clear watchdog timer

Compare Instructions:-

 CPFSGT f : Compare f with W and skip if f>W


 CPFSLT f :Compare f with W and skip if f<W
 CPFSEQ f :Compare f with W and skip if f=W

Pic Data Format:-

 HEX : 99H,99,h’99’,0efh,0x99
 BIN : b’101010011’
 DEC :d’29’
 ASCII :A’N’

REVIEW QUESTIONS:

a) Why are set-up registers used in PIC18F4520?


b) What are the timers present in PIC18F4520?
c) TIMER1 can be used a s timer as well as counter.(T/F)
d) What are the registers used for enabling serial communication in PIC called?
e) SPBRG stands for__________________
f) The interrupts are divided into two types__________ and____________.
g) ___________ register is used to set the priority of the interrupts?
h) Which pins are used as external clock inputs?

PROGRAMS:

a) Write a program to toggle PORTB when RA2 is given ‘1’ else toggle PORTC
b) Generate a square wave in RC5 of 100 ms using TIMER 1.
c) Transmit “CTTC BHUBANESWAR” to the virtual terminal if ‘0’ is received else transmit “WRONG KEY”.
d) Write a program to transmit a string and simultaneously toggle any PIN with the help of interrupts.
EMBEDDED SYSTEM DESIGN 92

ARM 7
(LPC2148)
EMBEDDED SYSTEM DESIGN 93

UNIT 12: AN INTRODUCTION TO THE ARM 7 ARCHITECTURE

The ARM architecture has evolved to a point where it supports implementations across a wide spectrum of
performance points. Over two billion parts have shipped, establishing it as the dominant architecture across many
market segments. The architectural simplicity of ARM processors has traditionally led to very small implementations,
and small implementations allow devices with very low power consumption. Implementation size, performance, and
very low power consumption remain key attributes in the development of the ARM architecture.

The ARM is a Reduced Instruction Set Computer (RISC), as it incorporates these typical RISC architecture
features:
 A Large Uniform Register File
 A load/store architecture, where data-processing operations only operate on register contents, not
directly on memory contents.
 Simple addressing modes, with all load/store addresses being determined from register contents and
instruction fields only
 Uniform and fixed-length instruction fields, to simplify instruction decode.

In addition, the ARM architecture provides:


 Control over both the Arithmetic Logic Unit (ALU) and shifter in most data-processing instructions to
maximize the use of an ALU and a shifter
 Auto-increment and auto-decrement addressing modes to optimize program loops
 Load and Store Multiple instructions to maximize data throughput
 Conditional execution of almost all instructions to maximize execution throughput.

These enhancements to a basic RISC architecture allow ARM processors to achieve a good balance of high
performance, small code size, low power consumption, and small silicon area.
EMBEDDED SYSTEM DESIGN 94

DATA SIZES AND INSTRUCTION SETS:


When used in relation to the ARM:
 Half word means 16 bits (two bytes)
 Word means 32 bits (four bytes)
 Double word means 64 bits (eight bytes)

Most ARMs implement two instruction sets:


 32-bit ARM Instruction Set
 16-bit Thumb Instruction Set

Latest ARM cores introduce a new instruction set Thumb-2


 Provides a mixture of 32-bit and 16-bit instructions
 Maintains code density with increased flexibility
 Jazelle-DBX cores can also execute Java byte code
EMBEDDED SYSTEM DESIGN 95

PROCESSOR MODES:
The ARM has seven basic operating modes:
 Each mode has access to own stack and a different subset of registers
 Some operations can only be carried out in a privileged mode

ARM REGISTERS:
ARM has 31 general-purpose 32-bit registers. At any one time, 16 of these registers are visible. All the
register specifiers in ARM instructions can address any of the 16 visible registers. These are the User mode registers.
User mode is different from all other modes as it is unprivileged, which means:
 User mode can only switch to another processor mode by generating an exception. The SWI instruction
provides this facility from program control.
 Memory systems and coprocessors might allow User mode less access to memory and coprocessor
functionality than a privileged mode.

Three of the 16 visible registers have special roles:


 Stack pointer: Software normally uses R13 as a Stack Pointer (SP). R13 is used by the PUSH and POP
instructions.
 Link register 14 is the Link Register (LR). This register holds the address of the next instruction after a Branch.
 Program counter Register 15 is the Program Counter (PC). It can be used in most instructions as a pointer to
the instruction which is two instructions after the instruction being executed.
The remaining 13 registers have no special hardware purpose. Their uses are defined purely by software.
EMBEDDED SYSTEM DESIGN 96

All processor state other than the general-purpose register contents is held in status registers. The current operating
processor status is in the Current Program Status Register (CPSR).

ARM INSTRUCTION SET:


 All instructions are 32 bits long / many execute in a single cycle.
 Instructions are conditionally executed.
 A load / store architecture
Example data processing instructions
SUB R0, R1, and #5
ADD R2, R3, R3, LSL #2
ADDEQ R5, R5, R6

Example branching instruction


B <Label>
EMBEDDED SYSTEM DESIGN 97

Example memory access instructions


LDR R0, [R1]
STRNEB R2, [R3, R4]
STMFD SP! , {R4-R8, LR}

THUMB INSTRUCTION SET:


 Thumb is a 16-bit instruction set
 Optimized for code density from C code
 Improved performance from narrow memory
 Subset of the functionality of the ARM instruction set

THE INSTRUCTION PIPELINE:


The ARM7uses a 3-stage pipeline in order to increase the
 Speed of the flow of instructions to the processor
 Allows several operations to be performed simultaneously, rather than serially

The PC points to the instruction being fetched, not executed.


 All operations here are on registers (single cycle execution)
 In this example it takes 6 clock cycles to execute 6 instructions
 Clock cycles per Instruction (CPI) = 1
EMBEDDED SYSTEM DESIGN 98

EXCEPTION AND INTERRUPT MODES:


The ARM 7 architecture has a total of six different operating modes, as shown below. These modes are
protected or exception modes which have associated interrupt sources and their own register sets.

USER: This mode is used to run the application code. Once in user mode the CPSR cannot be written to and modes
can only be changed when an exception is generated.
FIQ: (Fast Interrupt reQuest) This supports high speed interrupt handling. Generally it is used for a single critical
interrupt source in a system
IRQ: (Interrupt ReQuest) This supports all other interrupt sources in a system
Supervisor: A “protected” mode for running system level code to access hardware or run OS calls. The ARM 7 enters
this mode after reset.
Abort: If an instruction or data is fetched from an invalid memory region, an abort exception will be generated
Undefined Instruction: If a FETCHED opcode is not an ARM instruction, an undefined instruction exception will be
generated.
EMBEDDED SYSTEM DESIGN 99

LPC2148 supports 3 different data types as shown below.

LPC2148 PIN CONNECT BLOCK / GPIO:


The pin connect block allows selected pins of the microcontroller to have more than one function.
Configuration registers control the multiplexers to allow connection between the pin and the on chip peripherals.
LPC2148 has two 32-bit General Purpose I/O ports. Total of 30 input/output and a single output only pin out of
32 pins are available on PORT0. PORT1 has up to 16 pins available for GPIO functions. PORT0 and PORT1 are
controlled via two groups of 4 registers – IOPIN, IOSET, IODIR and IOCLR.
 IODIR - Controls the direction, either input(0) or output(1)
 IOSET - to set GPIO pin to high
 IOCLR - to set GPIO pin to low
 IOPIN - to read the current state of GPIO pins
 PINSEL - making a port as general purpose I/O

PINSEL
EMBEDDED SYSTEM DESIGN 100
EMBEDDED SYSTEM DESIGN 101
EMBEDDED SYSTEM DESIGN 102

PINSEL1:
EMBEDDED SYSTEM DESIGN 103
EMBEDDED SYSTEM DESIGN 104

PINSEL2:

UNIT 13: LPC2148 TIMER

LPC2148 comes loaded with two 32-bit-Timer blocks. Each Timer block can be used as a ‘Timer’ or as a
‘Counter’ and can be also used to demodulate PWM signals given as input. A timer has a Timer Counter(TC) and
Prescale Register(PR) associated with it. When Timer is Reset and Enabled TC is set to 0 and incremented by 1 every
‘PR+1′ clock cycles. When it reaches its maximum value it gets reset to 0 and hence restarts counting. Prescale
Register is used to define the resolution of the timer.
If PR=0 then TC is incremented every 1 clock cycle of the peripheral clock. If PR=1 then TC is incremented
every 2 clock cycles of peripheral clock and so on. By setting an appropriate value in PR we can make timer increment
or count: every peripheral clock cycle or 1 microsecond or 1 millisecond or 1 second and so on. Each Timer has four
32-bit Match Registers and four 32-bit Capture Registers.

MATCH REGISTERS: It can be used to Stop Timer on Match and trigger an optional interrupt. Reset Timer on Match
and trigger an optional interrupt. To count continuously and trigger an interrupt on match.
EMBEDDED SYSTEM DESIGN 105

CAPTURE REGISTERS: it is used to Capture Input signal. When a transition event occurs on a Capture pin , it can be
used to copy the value of TC into any of the 4 Capture Register or to generate an Interrupt. Hence these can be also
used to demodulated PWM signals
PR: PRESCALE REGISTER (32 BIT): Stores the maximum value of Prescale counter after which it is reset.

PC: PRESCALE COUNTER REGISTER (32 BIT): This register increments on every PCLK (Peripheral clock). This register
controls the resolution of the timer. When PC reaches the value in PR, PC is reset back to 0 and Timer Counter is
incremented by 1. Hence if PR=0 then Timer Counter Increments on every 1 PCLK. If PR=9 then Timer Counter
Increments on every 10th cycle of PCLK. Hence by selecting an appropriate prescale value we can control the
resolution of the timer.
TC : TIMER COUNTER REGISTER (32 BIT) : This is the main counting register. Timer Counter increments when PC
reaches its maximum value as specified by PR. If timer is not reset explicitly(directly) or by using an interrupt then it
will act as a free running counter which resets back to zero when it reaches its maximum value which is 0xFFFFFFFF.

TCR : TIMER CONTROL REGISTER :This register is used to enable , disable and reset TC. When bit0 is 1 timer is
enabled and when 0 it is disabled. When bit1 is set to 1 TC and PC are set to zero together in sync on the next positive
edge of PCLK. Rest of the bits of TCR is reserved.

CTCR: COUNT CONTROL REGISTER: Used to select Timer/Counter Mode. For our purpose we are always going to use
this in Timer Mode. When the value of the CTCR is set to 0×0 Timer Mode is selected.

MCR: MATCH CONTROL REGISTER: This register is used to control which all operations can be done when the value in
MR matches the value in TC. Bits 0, 1, 2 are for MR0, Bits 3, 4, 5 for MR1 and so on. Here’s a quick table which shows
the usage:
IR: INTERRUPT REGISTER: It contains the interrupt flags for 4 match and 4 capture interrupts. Bit0 to bit3 are for
MR0 to MR3 interrupts respectively. And similarly the next 4 for CR0-3 interrupts. when an interrupt is raised the
corresponding bit in IR will be set to 1 and 0 otherwise. Writing a 1 to the corresponding bit location will reset the
interrupt

EXAMPLE:
void delayMS(unsigned int milliseconds) //Using Timer0
{
    T0TCR = 0x02; //Reset Timer

    T0TCR = 0x01; //Enable timer


  
    while(T0TC < milliseconds); //wait until timer counter reaches the desired delay
  
    T0TCR = 0x00; //Disable timer
}
EMBEDDED SYSTEM DESIGN 106

UNIT 14: LPC2148 UART

The LPC2148 features multiple serial interfaces including two UARTs (16C550),
with 16 byte FIFO, two Fast I2C-bus (400 Kbit/s), SPI and SSP with buffering and variable data length.

RX Shift Register (U0RSR) accepts bits via RXD0. The CPU passes it to the UART0 RX Buffer Register FIFO to
await access via the generic host interface. The UART0 transmitter block, U0TX, accepts data written by the CPU and
buffers the data in the UART0 TX Holding Register FIFO (U0THR). The UART0 TX Shift Register (U0TSR) transmits the
data via the serial output pin, TXD0.
The UART0 Baud Rate Generator block, U0BRG, generates the timing enables used by the UART0 TX block. The
U0BRG clock input source is the APB clock (PCLK). The main clock is divided down per the divisor specified in the
U0DLL and U0DLM registers. Status information from the U0TX and U0RX is stored in the U0LSR. Control information
for the U0TX and U0RX is stored in the U0LCR.

LPC214x WDT:

The purpose of the watchdog is to reset the microcontroller within a reasonable amount of
time if it enters an erroneous state. When enabled, the watchdog will generate a system reset if the user program
fails to feed (or reload) the watchdog within a predetermined amount of time.

DESCRIPTION
The watchdog consists of a divide by 4 fixed pre-scaler and a 32-bit counter. The clock is
fed to the timer via a pre-scalar. The timer decrements when clocked. The minimum value
from which the counter decrements is 0xFF. Setting a value lower than 0xFF causes 0xFF
EMBEDDED SYSTEM DESIGN 107

to be loaded in the counter.


Hence the minimum watchdog interval is (TPCLK x 256 x 4) and the maximum watchdog interval is (TPCLK x
232 x 4) in multiples of (TPCLK x 4). The watchdog should be used in the following manner:
• Set the watchdog timer constant reload value in WDTC register.
• Setup mode in WDMOD register.
• Start the watchdog by writing 0xAA followed by 0x55 to the WDFEED register.
• Watchdog should be fed again before the watchdog counter underflows to prevent
reset/interrupt.

When the Watchdog counter underflows, the program counter will start from 0x0000 0000 as in the case of
external reset. The Watchdog Time-Out Flag (WDTOF) can be examined to determine if the watchdog has caused the
reset condition. The WDTOF flag must be cleared by software.

SERIAL COMMUNICATION

 In ARM the serial communication is possible in asynchronous mode. So only UART (Universal Asynchronous
Receiver and Transmitter) is present in ARM
 Unlike 8051 and PIC arm has two UARTs (UART0 , UART1)
 These UARTs are selectable by PINSEL0 register
 For UART0 the value of PINSEL0=0x00000005
 For UART1 the value of PINSEL0=0x00050000

FEATURES
 16 byte Receive and Transmit FIFOs.
 Register locations confirm to ‘550 industry standard.
 Receiver FIFO trigger points at 1, 4, 8, and 14 bytes.
 Built-in fractional baud rate generator with auto-bauding capabilities.
 Mechanism that enables software and hardware flow control implementation.
 UART1 has got an additional modem interface.
 Standard modem interface signals included with flow control (auto-CTS/RTS) fully supported in hardware
(LPC2144/6/8 only).

REGISTERS REQUIRED FOR SERIAL COMMUNICATION:


 UxLCR (Line Control Register)
 UxDLL (Divisor Latch LSB)
 UxDLM (Divisor latch MSB)
 UxLSR (Line Status Register)
 UxTHR (Transmit Holding Register)
 UxRBR (Receiver Buffer Register)
 NOTE : - Here x denotes the number of UART. 1 for UART1 and 0 for UART0

UxLCR (Line Control Register)


EMBEDDED SYSTEM DESIGN 108

 It is a 8-bit register.
 It determines the format of data character to be transmitted or received.

BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0

Divisor Break Parity Parity Parity Stop Select Word Word


Latch Control Select bit 1 Select bit 0 Enable bit length length
access bit select bit 1 select bit 0

BIT NAME BIT NO. DESCRIPTION

Divisor Latch Access 7 1- Enables Access to Divisor latch


bit 0- Disables Access to Divisor latch
Break Control bit 6 1- Enables Break Transmission
0- Disables Break Transmission
Parity Select bit 5-4 00- Odd parity
01- Even Parity
10- Forced “1” stick parity
11- Forced “0” stick parity
Parity Enable bit 3 1- Enable Parity generation and checking
0- Disable Parity generation and checking
Stop Select bit 2 1- 2 stop bits
0- 1 stop bit

Word Length Select 1-0 00- 5 bit character length


bit 01- 6 bit character length
10- 7 bit character length
11- 8 bit character length
UxDLL and UxDLM (Divisor Latch Registers):

 The UART0 Divisor Latch is part of the UART0 Fractional Baud Rate Generator and holds the value used to divide
the clock supplied by the fractional pre-scaler in order to produce the baud rate clock, which must be 16x the
desired baud rate.
 The U0DLL and U0DLM registers together form a 16 bit divisor where U0DLL contains the lower 8 bits of the
divisor and U0DLM contains the higher 8 bits of the divisor.
 Formula for UxDLL and UxDLM

Baud Rate = Frequency of crystal oscillator (Pclk)


16 x (UxDLL UxDLM)
EMBEDDED SYSTEM DESIGN 109

EXAMPLE:
 Assume,
Baud rate = 9600
Pclk= 60 MHz
Hence according to the formula
9600 = 60 MHz
16 x (UxDLL . UxDLM)
UxDLM.UxDLL = 60 MHz
16 x 9600
= 390.6 (Decimal)
= 186 (Hexadecimal)
So UxDLM = 0x01
UxDLL = 0x86
UxLSR (Line Status Register)
 It is a 8-bit register.
 It is a read-only register that provides status information of UART Tx and Rx blocks.

BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0

Error in Transmitter THR Break Framing Parity Overrun Receiver


Rx empty empty Interrupt error Error Error Data Ready

BIT NAME BIT NO. DESCRIPTION

Error in Rx 7 1- UxRBR contains Rx error


0- UxRBR contains no Rx errors
Transmitter 6 1- UxTHR and UxTSR are empty
empty 0- UxTHR or UxTSR contains some data
THR empty 5 1- THR is empty
0- THR contains some data
Break Interrupt 4 1- Break interrupt is active
0- Break interrupt is inactive
Framing error 3 1- Framing error is active
0- Framing error is inactive
Parity error 2 1- Parity error is active
0- Parity error is inactive
Overrun error 1 1- Overrun error is active
0- Overrun error is inactive
Receiver Data 0 1- UxRBR contains data
Ready 0- UxRBR is empty
EMBEDDED SYSTEM DESIGN 110

UxTHR (Transmit Holding Register):


 The U0THR is the top byte of the UART0 TX FIFO. The top byte is the newest character in the TX FIFO and can
be written via the bus interface. The LSB represents the first bit to transmit.
 The Divisor Latch Access Bit (DLAB) in U0LCR must be zero in order to access the U0THR. The U0THR is always
Write Only.

UxRBR (Receiver Buffer Register):


 The U0RBR is the top byte of the UART0 Rx FIFO. The top byte of the Rx FIFO contains the oldest character
received and can be read via the bus interface. The LSB (bit 0) represents the “oldest” received data bit. If the
character received is less than 8 bits, the unused MSBs are padded with zeroes.
 The Divisor Latch Access Bit (DLAB) in U0LCR must be zero in order to access the U0RBR. The U0RBR is always
Read Only.

PINS DEFINED FOR SERIAL COMMUNICATION:


 UART0
P0.0 => TXD
P0.1 => RXD
 UART1
P0.8 => TXD
P0.9 => RXD
PROGRAMMING STEPS
TRANSMISSION:
1) Select the desired UART (UART1 or UART0) by giving the value of PINSEL0
2) Gain access to the divisor latch registers and select the data format (8 – bit) by giving the value of UxLCR
(0x83)
3) Assign the value of Divisor Latch Registers (UxDLL and UxDLM) for desired frequency.
4) Disable the divisor latch access once the value is assigned in order to access the UxTHR i.e. UxLCR=0x03
5) Check the Status of UxLSR. If the THR is empty i.e If UxLSR = 0x20, load the data is UxTHR.
6) Go to step 5
NOTE :- Assign the desired frequency through PLL method as taught previously in Timer

Transmit ‘x’ at 9600 baud rate.


#include<lpc21xx.h>
void main()
{ PINSEL0=0X05;
U0LCR=0X83;
U0DLL=0X86;
U0DLM=0X01;
U0LCR=0X03;
PLLCON=0X03;
PLLCFG=0X24;
PLLFEED=0X55;
PLLFEED=0XAA;
while(!(PLLSTAT & 1<<10));
EMBEDDED SYSTEM DESIGN 111

VPBDIV=0x01;
while(1)
{
while(!(U0LSR & 0x20));
U0THR=‘x’;
}
}
RECEPTION:
1) Select the desired UART (UART1 or UART0) by giving the value of PINSEL0
2) Gain access to the divisor latch registers and select the data format (8 – bit) by giving the value of UxLCR
(0x83)
3) Assign the value of Divisor Latch Registers (UxDLL and UxDLM) for desired frequency.
4) Disable the divisor latch access once the value is assigned in order to access the UxTHR i.e. UxLCR=0x03
5) Check the Status of UxLSR. If the UxRBR contains data i.e If UxLSR = 0x01, move the data of UxRBR to another
memory location.
6) Go to step 5
NOTE :- Assign the desired frequency through PLL method as taught previously in Timer

Receive any data from keyboard and display on Port1.


#include<lpc21xx.h>
void main()
{ IO1DIR= 0xFFFFFFFF;
PINSEL0=0X05;
U0LCR=0X83;
U0DLL=0X86;
U0DLM=0X01;
U0LCR=0X03;
PLLCON=0X03;
PLLCFG=0X24;
PLLFEED=0X55;
PLLFEED=0XAA;
while(!(PLLSTAT & 1<<10));
VPBDIV=0x01;
while(1)
{
while(!(U0LSR & 0x01));
IO1PIN=(U0RBR<<16);
}
}

UNIT 15: LPC2148 INTERRUPTS:


EMBEDDED SYSTEM DESIGN 112

Interrupts in LPC214x are handled by Vectored Interrupt Controller (VIC) and are classified into 3 types based
on the priority levels.
 Fast Interrupt Request i.e. FIQ : which has highest priority
 Vectored Interrupt Request i.e. Vectored IRQ: which has ‘middle’ or priority between FIQ and Non-Vectored
IRQ.
 Non-Vectored IRQ: This has the lowest priority.

The difference between Vectored IRQ (VIRQ) and Non-Vectored IRQ (NVIRQ) is that VIRQ has dedicated IRQ
service routine for each interrupt source which while NVIRQ has the same IRQ service routine for all Non-Vectored
Interrupts.

VIC, as per its design, can take 32 interrupt request inputs but only 16 requests can be assigned to Vectored
IRQ interrupts in its LCP214x Implementation. We are given a set of 16 vectored IRQ slots to which we can assign any
of the 22 requests that are available in LPC2148. The slot numbering goes from 0 to 15 with slot no. 0 having highest
priority and slot no. 15 having lowest priority.

Example: For example if you working with 2 interrupt sources say. UART0 and TIMER0. Now if you want to
give TIMER0 a higher priority than UART0 then assign TIMER0 interrupt a lower number slot than UART0 Like hook up
TIMER0 to slot 0 and UART0 to slot 1 or TIMER0 to slot 4 and UART to slot 9 or whatever slots you like. The number of
the slot doesn’t matter as long TIMER0 slot is lower than UART0 slot.

Now we will have a look at some of the important Registers that are used to implement interrupts in lpc214x:
1. VICIntSelect (R/W): This register is used to select an interrupt as IRQ or as FIQ. Writing a 0 at a given bit
location will make the corresponding interrupt as IRQ and writing a 1 will make it FIQ.

2. VICIntEnable (R/W): This is used to enable interrupts. Writing a 1 at a given bit location will make the
corresponding interrupt Enabled. If this register is read then 1′s will indicate enabled interrupts and 0′s as
disabled interrupts.

3. VICIntEnClr (R/W): This register is used to disable interrupts. This is similar to VICIntEnable expect writing a 1
here will disabled the corresponding Interrupt. This has an effect on VICIntEnable since writing at bit given
location will clear the corresponding bit in the VICIntEnable Register.
EMBEDDED SYSTEM DESIGN 113

4. VICIRQStatus (R): This register is used for reading the current status of the enabled IRQ interrupts. If a bit
location is read as 1 then it means that the corresponding interrupt is enabled and active.

5. VICFIQStatus (R): Same as VICIRQStatus except it applies for FIQ.

6. VICSoftInt: This register is used to generate interrupts using software i.e. manually generating interrupts using
code i.e. the program itself. If you write a 1 at any bit location then the corresponding interrupt is triggered
i.e. it forces the interrupt to occur.

7. VICSoftIntClear: This register is used to clear the interrupt request that was triggered (forced) using
VICSoftInt. Writing a 1 will release (or clear) the forcing of the corresponding interrupt.

8. VICVectCntl0 to VICVectCntl15 (16 registers in all): These are the Vector Control registers. These are used to
assign a particular interrupt source to a particular slot. As mentioned before slot 0 i.e. VICVectCntl0 has
highest priority and VICVectCntl15 has the lowest. Each of this registers can be divided into 3 parts: {Bit0 to
bit4}, {Bit 5}, {and rest of the bits}.The first 5 bits i.e. Bit 0 to Bit 4 contain the number of the interrupt
request which is assigned to this slot.

9. VICVectAddr: This must not be confused with the above set of 16 VICVecAddrX registers. When an interrupt is
triggered this register holds the address of the associated ISR i.e. the one which is currently active. Writing a
value i.e. dummy write to this register indicates to the VIC that current Interrupt has finished execution. In
this tutorial the only place we’ll use this register .is at the end of the ISR to signal end of ISR execution.

10. VICDefVectAddr: This register stores the address of the “default/common” ISR that must be called when a
Non-Vectored IRQ occurs.
EMBEDDED SYSTEM DESIGN 114

REVIEW QUESTIONS:

a) What are the two instruction sets of LPC2148


b) ARM7 uses ____-stage pipeline.
c) PINSEL is used to__________________.
d) What is the difference between IODIR and IOPIN?
e) The different types of interrupts are ___________________.

PROGRAMS:

e) Write a program to toggle PORT0 continuously.


f) Write a program to rotate a single bit in PORT0 continuously.
g) Write a code to generate delay using TIMERS of LPC2148
EMBEDDED SYSTEM DESIGN 115

BASICS
OF
Embedded C
PROGRAMMING
EMBEDDED SYSTEM DESIGN 116

UNIT 13: EMBEDDED C

INTRODUCTION:
The C programming language was developed at Bell Labs during the early 1970's. Quite unpredictably it
derived from a computer language named B and from an earlier language BCPL. As a programming language C
program stores values in variables. Programs are structured by defining functions. Program flow is controlled using
loops, if-statements and function calls. Related data can be stored together in arrays or structure.
C is a so-called a compiled language. This means that once we write our C program, we must run it through a C
compiler to turn our program into an executable that the CPU can run (execute). The C program is the human-
readable form, while the executable that comes out of the compiler is the machine-readable and executable form
(i.e. a list of CPU instructions).

A SIMPLE C PROGRAM:
/* PROGRAM TO SEND 55H TO PORT1 AND AAH TO PORT2 */

#include<reg51.h>
void main()
{
while(1)
{
P1=0X55;
P2=0XAA;
}
}

Comments:
 Text surrounded by /* and */ is ignored by computer
 Used to describe program

#include <reg51.h>
 Preprocessor directive: Tells computer to load contents of a certain file
 <reg51.h> allows standard registers and operation of 8051 microcontroller. But in case of Embedded Systems,
the program for each microcontroller needs to be started with its own Preprocessor directive or header file.
E.g.
8051 #include<reg51.h>
PIC18F452 #include<P18F452.h>
LPC2148/38 #include<LPC21XX.h>

void main()
 C programs contain one or more functions, exactly one of which must be main
 Parenthesis used to indicate a function
 void means that main "returns" an null value
 Braces ({ and }) indicate a block
EMBEDDED SYSTEM DESIGN 117

while(1)
Instructs computer to perform an infinite loop
This will run the block of code within “ { } “ infinite number of times
Right brace } Indicates end of main has been reached

VARIABLE DECLARATION:
int integer1, integer2, sum;
 Variables: locations in memory where a value can be stored
 int means the variables can hold integers (-1, 3, 0, 47)
 Variable names (identifiers)
 integer1, integer2, sum
 Identifiers: consist of letters, digits (cannot begin with a digit) and underscores( _ )
 Case sensitive

‘ = ‘ (assignment operator)
 Assigns a value to a variable
 Variable receiving value on left

sum = variable1 + variable2; /* sum gets variable1 + variable2 */

C DATATYPES & SIZES:


char : 8 bits = 1 byte
short int : 16 bits = half word
int, long int : 32 bits = 1 word
float : 32 bits = 1 word
double :64 bits = 2 words

 Char, int and long into can be signed or unsigned.


 Signed values are represented in 2’s complement form.
 Float and double are signed floating point numbers

ARITHMETIC OPERATORS:

 Use ‘ * ’ for multiplication and ‘ /’ for division


 7 / 5 evaluates to 1 : Modulus operator(%) returns the remainder
 7 % 5 evaluates to 2
EMBEDDED SYSTEM DESIGN 118

OPERATOR PRECEDENCE:

Example: Find the average of three variables a, b and c


 Do not use: a + b + c / 3
 Use: (a + b + c ) / 3

DECISION MAKING: EQUALITY AND RELATIONAL OPERATORS:


Executable statements
 Perform actions (calculations, input/output of data)
 Perform decisions
 May want to print "pass" or "fail" given the value of a test grade

if control structure:
if( condition)
{
//True Statement;
}
else
{
//False Statement ;
}

 If a condition is true, then the body of the if statement executed


 0 is false, non-zero is true
 Control always resumes after the if structure

EQUALITY AND RELATIONAL OPERATORS:


EMBEDDED SYSTEM DESIGN 119

Implementing Loops:

for loop:
for (initialization; condition; increment/decrement)

{
//Statements;
}

 E.g. “for (k = 100; k!= 0; k --)” and “ for(k = 0; k < 100; k++)” both are almost the same.
 Array elements are often accessed in loops, with incrementing or decrementing index.
 Instead, using a pointer and moving it ahead / backwards is often better.

while loop:
while (condition)
{
//statements ;
}
 The statements will be execute only till the condition inside the parenthesis is satisfied.

switch case:
The switch case statements allow controlling complex conditional and branching operations. It includes any number
of case instances, but should not have the same value.

switch (n)
{
case constant1:
//code/s to be executed if n equals to constant1;
break;
case constant2:
//code/s to be executed if n equals to constant2;
break;
default:
//code/s to be executed if n doesn't match to any cases;
}

The value of n is either an integer or a character in above syntax. If the value of n matches constant in case,
the relevant codes are executed and control moves out of the switch statement. If the n doesn't matches any of the
constant in case, then the default codes are executed and control moves out of switch statement.
EMBEDDED SYSTEM DESIGN 120

INTERFACING
EMBEDDED SYSTEM DESIGN 121

LCD INTERFACING
LCD display is an inevitable part in almost all embedded projects and this is about  interfacing 16×2 LCD with
8051 microcontroller. By knowing it you can easily design embedded projects like digital voltmeter / ammeter,
digital clock, home automation displays, status indicator display, digital code locks, digital speedometer/ odometer,
display for music players etc etc. Thoroughly going through this article will make you able to display any text
(including the extended characters) on any part of the 16×2 display screen. In order to understand the interfacing
first you have to know about the 16×2 LCD module.

16×2 LCD MODULE:


16×2 LCD module is a very common type of LCD module that is used in 8051 based embedded projects. It
consists of 16 rows and 2 columns of 5×7 or 5×8 LCD dot matrices. It is available in a 16 pin package with back light
contrast adjustment function and each dot matrix has 5×8 dot resolution.

VEE PIN is meant for adjusting the contrast of the LCD display and the contrast can be adjusted by varying the
voltage at this pin. This is done by connecting one end of a POT to the VCC (5V), other end to the VSS (GROUND)
and connecting the centre terminal (wiper) of of the POT to the VEE pin. See the circuit diagram for better
understanding.
There are two built in registers namely DATA REGISTER and COMMAND REGISTER.  Data register is for
placing the data to be displayed, and the command register is to place the commands.
The 16×2 LCD module has a set of commands each meant for doing a particular job with the display. We will discuss
in detail about the commands later. High logic at the RS pin will select the data register and Low logic at the RS PIN
will select the command register.

If we make the RS PIN high and the put a data in the 8 bit data line (DB0 to DB7), the LCD module
will recognize it as a data to be displayed.  If we make RS PIN low and put a data on the data line, the module will
recognize it as a command.

The pin numbers, their name and corresponding functions are shown in the table below.
EMBEDDED SYSTEM DESIGN 122

R/W PIN is meant for selecting between read and write modes. High level at this pin enables read mode and low
level at this pin enables write mode.

E PIN is for enabling the module. A high to low transition at this pin will enable the module.

DB0 to DB7 is the data pins. The data to be displayed and the command instructions are placed on these pins.

LED+ is the anode of the back light LED and this pin must be connected to Vcc through a suitable series current
limiting resistor. LED- is the cathode of the back light LED and this pin must be connected to ground.

16×2 LCD MODULE COMMANDS:

16×2 LCD module has a set of preset command instructions. Each command will make the module to do a
particular task. The commonly used commands and their function are given in the table below.

COMMAND APPLICATION
01H Clear Display Screen
EMBEDDED SYSTEM DESIGN 123

02H Return Home

04H Decrement Cursor

06H Increment Cursor

05H Shift Display Right

07H Shift Display Left

08H Display off, Cursor off

AH Display off, Cursor on

CH Display on, Cursor off

EH Display on, Cursor Blinking

FH Display on, Cursor Blinking

10H Shift Cursor position to left

14H Shift Cursor position to right

18H Shift the entire display to left

1CH Shift the entire display to right

80H Force cursor to begin from the 1st line

C0H Force cursor to begin from the 2nd line

38H 2 lines and 5 x 7 matrix

SENDING DATA TO THE LCD:


Steps for sending data to the LCD module are given below. I have already said that the LCD module has pins
namely RS, R/W and E. It is the logic state of these pins that make the module to determine whether a given data
input is a command or data to be displayed.
 Make R/W low.
 Make RS=0 if data byte is a command and make RS=1 if the data byte is a data to be displayed.
 Place data byte on the data register.
 Pulse E from high to low.
 Repeat above steps for sending another data.
EMBEDDED SYSTEM DESIGN 124

In the above picture, P2.0 to P2.7 pins of the microcontroller is connected to the DB0 to DB7 pins of the
module respectively and through this route the data goes to the LCD module.  P3.0, P3.1 and P3.2 are connected to
the RS, RW, E pins of the microcontroller and through this route the control signals are transferred to the LCD
module. Resistor limits the current through the back light LED and so do the back light intensity. POT is used for
adjusting the contrast of the display.

4 X 4 KEYPAD INTERFACING
EMBEDDED SYSTEM DESIGN 125

Matrix Keypads are commonly used in calculators, telephones etc where a number of input switches are
required. We know that matrix keypad is made by arranging push button switches in row and columns. In the
straight forward way to connect a 4×4 keypad (16 switches) to a microcontroller we need 16 inputs pins. But by
connecting switches in the following way we can read the status of each switch using 8 pins of the microcontroller.

SCANNING A MATRIX KEYPAD:


There are many methods depending on how you connect your keypad with your controller, but the basic
logic is same.
Initially all switches are assumed to be released. So there is no connection between the rows and
columns. When any one of the switches is pressed, the corresponding rows and columns are connected (short
circuited). This will drive that column pin (initially high) low. Using this logic, the button press can be detected. The
colors red and black are for logic high and low respectively.  Here are the steps involved in determining the key that
was pressed.

STEP 1:
The first step involved in interfacing the matrix keypad is to write all logic 0’s to the rows and all logic 1’s to
the columns. In the image, black line symbolizes logic 0 and red line symbolizes logic 1. For now let us assume that,
the circled key is pressed and see how the key press can be detected by a software routine.
EMBEDDED SYSTEM DESIGN 126

STEP 2:
Now the software has to scan the pins connected to columns of the keypad. If it detects logic 0 in any one of
the columns, then a key press was made in that column. This is because the event of the switch press shorts the C2
line with R2. Hence C2 is driven low. Note: colour of the lines indicates the logic values they return.

STEP 3:
Once the column corresponding to the key pressed is located, the next thing that the software has to do is
to start writing logic 1’s to the rows sequentially (one after the other) and check if C2 become high. The logic is that
if a button in that row was pressed, then the value written to that row will be reflected in determined column (C2) as
they are short circuited. Note: colour of the lines indicates the logic values they return.

STEP 4:
The procedure is followed till C2 goes high with logic high is written to a row. In this case, logic high to the
second row will be reflected in the second column. Note: colour of the lines indicates the logic values they return.
EMBEDDED SYSTEM DESIGN 127

We already know the key press happened at column 2. Now we have detected that the key is in row 2. So,
the position of the key in the matrix is (2, 2) Once this is detected, it’s up to us to name it or provide it with a task in
the event of the key press.

DC MOTOR INTERFACING

When we talk about controlling the robot, the first thing comes into the mind is controlling DC motors.
Interfacing DC motor to the microcontroller is very important concept in Robotic applications. By interfacing DC
motor to the microcontroller, we can do many things like controlling the direction of the motor, controlling the
speed of the motor.
EMBEDDED SYSTEM DESIGN 128

DC MOTOR CIRCUIT PRINCIPLE:


The maximum output current of microcontroller pin is 15mA at 5V. But the power requirements of most of
DC motors is out of reach of the microcontroller and even the back emf (electro motive force) which is produced by
the motor may damage the microcontroller. Hence it is not good to interface DC motor directly to the controller. So
use motor driver circuit in between of DC motor and controller.

Here, we are using L293D motor driver IC to drive DC motors. Using this IC, we can drive 2 DC motors at a
time. For this IC motor supply is variable 4.5 to 36V and it provides maximum current of 600mA.

INTERFACING DC MOTOR TO 8051 CIRCUIT DESIGN:


The major components in the above circuit diagram are at89c51 microcontroller and motor driver. Here the
motor driver input pins IN1, IN2 are connected to the P3.0 and P3.1 respectively to control the motor directions. DC
motor is connected to output terminals of L293D. EN1 pin is connected to the 5V DC to drive the motor.

Switches are connected to the P2.0 and P2.1 in pull down configuration. First switch rotates the motor in
clockwise direction and second switch rotates the motor in anti clockwise direction. 8th pin of motor driver is
connected to the battery directly.

L293D MOTOR DRIVER:


L293D is a quadruple H- bridge motor driver, as the name suggests it used to drive the DC motors. This IC
works based on the concept of H- Bridge. H-bridge is a circuit which allows the voltage in either direction to control
the motor direction.

There are 4 input pins for L293D. Motors directions depends on the logic inputs applied at this pins. EN1 and
EN2 must be high to drive the 2 DC motors. Algorithm for Interfacing DC Motor to 8051:
1. Declare P2.1 and P2.2 as inputs for motor 1 (IN1 & IN2) and P3.1 and P3.2 for motor 2 (IN3 &IN4).
2. The motor 1 is connected to OUT1 & OUT2
3. The motor 2 is connected to OUT3 & OUT4
4. The push buttons are used for giving the choice of rotation for the respective motors.

IN1=0 and IN2=0 -> Motor1 idle


IN1=0 and IN2=1 -> Motor1 Anti-clock wise direction
IN1=1 and IN2=0 -> Motor1 Clock wise direction
IN1=1 and IN2=1 -> Motor1 idle
IN3=0 and IN4=0 -> Motor2 idle
IN3=0 and IN4=1 -> Motor2 Anti-clock wise direction
IN3=1 and IN4=0 -> Motor2 Clock wise direction
IN3=1 and IN4=1 -> Motor2 idle
EMBEDDED SYSTEM DESIGN 129

STEPPER MOTOR INTERFACING


A stepper motor is a brushless and synchronous motor which divides the complete rotation into number of
steps. Each stepper motor will have some fixed step angle and motor rotates at this angle. Here in this article,
interfacing of stepper to 8051 and ULN 2003 is explained

STEPPER MOTOR CONTROL CIRCUIT PRINCIPLE:


  The main principle of this circuit is to rotate the stepper motor step wise at a particular step angle.
The ULN2003 IC is used to drive the stepper motor as the controller cannot provide current required by the motor.
EMBEDDED SYSTEM DESIGN 130

STEPPER MOTOR CONTROL CIRCUIT DESIGN:


The circuit consists of AT89C51 microcontroller, ULN2003A, Motor. AT89c51 is low power, high-
performance, CMOS 8bit, 8051 family microcontroller. It has 32 programmable I/O lines. It has 4K bytes of Flash
programmable and erasable memory. An external crystal oscillator is connected at the 18 and 19 pins of the
microcontroller. Motor is connected to the port2 of the microcontroller through a driver IC.
The ULN2003A is a current driver IC. It is used to drive the current of the stepper motor as it requires more
than 60mA of current. It is an array of Darlington pairs. It consists of seven pairs of Darlington arrays with common
emitter. The IC consists of 16 pins in which 7 are input pins, 7 are output pins and remaining are VCC and Ground.
The first four input pins are connected to the microcontroller. In the same way, four output pins are connected to
the stepper motor.
Stepper motor has 6 pins. In these six pins, 2 pins are connected to the supply of 12V and the remaining is
connected to the output of the stepper motor. Stepper rotates at a given step angle. Each step in rotation is a
fraction of full cycle. This depends on the mechanical parts and the driving method.
Similar to all the motors, stepper motors will have stator and rotor. Rotor has permanent magnet and stator
has coil. The basic stepper motor has 4 coils with 90 degrees rotation step. These four coils are activated in the cyclic
order. The below figure shows you the direction of rotation of the shaft. There are different methods to drive a
stepper motor. Some of these are explained below.

Full Step Drive: In this method two coils are energized at a time. Thus, here two opposite coils are excited at a time. 

Half Step Drive: In this method coils are energized alternatively. Thus it rotates with half step angle. In this method,
two coils can be energized at a time or single coil can be energized.
EMBEDDED SYSTEM DESIGN 131

7-SEGMENT INTERFACING
7 segment displays consists of 7 segments and a dot. Actually each segment and dot is LEDs (Light Emitting
Diodes). Each segment including dot are total 8 LEDs.

Light Emitting Diode like an ordinary diode passes current in one direction (forward biased) and block in
other (reverse biased) direction. Each LED has 2 pins one for anode and other for cathode. In common anode all anode
terminals are connected together to form a common connection and remaining 8 cathodes are provided for negative
side supply of individual LED.
We connect common wire with positive supply and provide negative supply to appropriate LED segments to
switch on and make a specific pattern on the whole display. In common cathode display all pins are opposite to
common anode. All cathode terminals are connected to form a common connection and all other 8 pins are anodes

COMMON CATHODE COMMON ANODE

TASKS:
EMBEDDED SYSTEM DESIGN 132

1. Design a PASSWORD PROTECTED DOOR LOCK SYSTEM, where the input is given through the 4X4 KEYPAD
and the message is displayed in a 16X2 LCD .If the password is matched then activates the DC MOTORS to
open the door.

2. Design a VISITOR COUNTER. Every time the ENTER SENSOR is activated, it will increase the count value, while
the activation of the EXIT SENSOR will decrease the count value. Display the count value in a SEVEN
SEGMENT DISPLAY.

3. Design a FOUR WAY TRAFFIC CONTROLLER, and display the seconds left in a SEVEN SEGMENT DISPLAY.

4. Design a HOME AUTOMATION SYSTEM using RFID module.

5. Design a DIGITAL CLOCK, USING ANY THREE PORTS TO DISPLAY THE SECONDS, MINUTES AND HOURS.
EMBEDDED SYSTEM DESIGN 133

SOFTWARE STEPS
FOR
PROTEUS

STEP 1: DOUBLE-CLICK ON THE “ISIS 7 PROFESSIONAL” ICON ON THE DESKTOP


EMBEDDED SYSTEM DESIGN 134

STEP 2: CLICK ON THE TERMINALS MODE TO INSERT THE POWER,GROUND IF REQUIRED

STEP 3: ON THE SOFTWARE WINDOW,CLICK ON THE COMPONENT MODE AND CLICK ON ‘P’ TO PICK THE
COMPONENTS REQUIRED
EMBEDDED SYSTEM DESIGN 135

STEP 4: ON THE “PICK DEVICES” WINDOW, TYPE AND SEARCH FOR THE REQUIRED COMPONENT

STEP 5: SELECT THE COMPONENT AND CLICK ON “OK”


EMBEDDED SYSTEM DESIGN 136

STEP 6: PLACE THE COMPONENT ON THE WINDOW

STEP 7: CONNECT ALL THE COMPONENTS IN THE SOFTWARE WINDOW


EMBEDDED SYSTEM DESIGN 137

STEP 8: DOUBLE CLICK ON THE MICROCONTROLLER , CHANGE THE CLOCK FREQUENCY AND CLICK ON “PROGRAM
FILE” TO LOAD THE PROGRAM

STEP 9: SELECT THE HEX FILE IN YOUR PROJECT LOCATION


EMBEDDED SYSTEM DESIGN 138

STEP 10: CLICK ON “PLAY” TO RUN YOUR PROGRAM


EMBEDDED SYSTEM DESIGN 139

SOFTWARE STEPS
FOR
FLASH MAGIC

STEP 1: DOUBLE CLICK ON THE “FLASH MAGIC “ ICON ON YOUR DESKTOP


EMBEDDED SYSTEM DESIGN 140

STEP 2: CLICK ON “SELECT DEVICE” TO CHOOSE THE MICROCONTROLLER TO BE USED, CHOOSE “89V51RD2”
EMBEDDED SYSTEM DESIGN 141

STEP 3: SELECT THE COM PORT YOU WILL BE USING.(COM 1)

STEP 4: SELECT THE BAUDRATE AS “9600”


EMBEDDED SYSTEM DESIGN 142

STEP 5: CHECK ON THE OPTION “ERASE ALL FLASH”

STEP 6: BROWSE FOR THE HEX FILE


EMBEDDED SYSTEM DESIGN 143

STEP 7: CHECK ON THE OPTION “VERIFY AFTER PROGRAMMING” AND CLICK ON START”

You might also like