Embedded System Material
Embedded System Material
Embedded System Material
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
1. ARCHITECTURE OVERVIEW
2. PIN CONFIGURATION
3. INPUT/OUTPUT PINS
4. MEMORY
5. ADDRESSING MODES
INTERFACING 118
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
4. USER INTERFACES:
5. HARDWARE
Hardware includes the chips, wires, circuit boards, buttons and displays.
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.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
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.
Ways to recover from errors — both software bugs such as memory leaks, and also soft errors in the hardware:
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.
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.
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
8051
MICROCONTROLLER
EMBEDDED SYSTEM DESIGN 12
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.
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
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
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
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
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
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
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.
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.
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.
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.
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:
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
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.
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
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
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.
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).
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.
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
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.
#include<reg51.h>
void main()
{
TMOD=0X01;
while(1)
{
TL0=0;
TH0=0;
TR0=1;
while(TF0==0);
TR0=0;
TF0=0;
P1=~P1;
}
}
register TL0 operating as a timer (normally 8-bit), while the value from which counting should start is saved in the TH0
register.
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 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
#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
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).
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
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:
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
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.
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.
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
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
#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
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.
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)
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
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;
}}
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.
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
REVIEW QUESTIONS:
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
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.
PERIPHERAL FEATURES:
Three external interrupt pins
Timer0 module: 8-bit/16-bit timer/counter with 8-bit programmable prescaler
EMBEDDED SYSTEM DESIGN 47
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)
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
DEVICE FEATURES:
EMBEDDED SYSTEM DESIGN 50
PIN CONFIGURATION:
EMBEDDED SYSTEM DESIGN 51
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
RC4/SDI/SDA 23 Digital I/O,Serial Clk input For SPI & I/O for IC2
MEMORY ORGANISATION:
There are three memory blocks in Enhanced MCU devices. These memory blocks are:
Program Memory
Data RAM
Data EEPROM
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).
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.
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
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
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
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
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.
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.
#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>).
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
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.
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>).
BIT DESCRIPTION
NA
ME
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.
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
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; } }
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.
- 3 Unimplemented:
Read as '0'
- 1 Unimplemented:
Read as '0'
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
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
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 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
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.
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
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
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
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:-
HEX : 99H,99,h’99’,0efh,0x99
BIN : b’101010011’
DEC :d’29’
ASCII :A’N’
REVIEW QUESTIONS:
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
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.
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
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.
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).
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
PINSEL
EMBEDDED SYSTEM DESIGN 100
EMBEDDED SYSTEM DESIGN 101
EMBEDDED SYSTEM DESIGN 102
PINSEL1:
EMBEDDED SYSTEM DESIGN 103
EMBEDDED SYSTEM DESIGN 104
PINSEL2:
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
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
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).
It is a 8-bit register.
It determines the format of data character to be transmitted or received.
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
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.
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
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.
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:
PROGRAMS:
BASICS
OF
Embedded C
PROGRAMMING
EMBEDDED SYSTEM DESIGN 116
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
ARITHMETIC OPERATORS:
OPERATOR PRECEDENCE:
if control structure:
if( condition)
{
//True Statement;
}
else
{
//False Statement ;
}
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.
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 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
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.
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
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.
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.
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.
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
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.
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 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 8: DOUBLE CLICK ON THE MICROCONTROLLER , CHANGE THE CLOCK FREQUENCY AND CLICK ON “PROGRAM
FILE” TO LOAD THE PROGRAM
SOFTWARE STEPS
FOR
FLASH MAGIC
STEP 2: CLICK ON “SELECT DEVICE” TO CHOOSE THE MICROCONTROLLER TO BE USED, CHOOSE “89V51RD2”
EMBEDDED SYSTEM DESIGN 141
STEP 7: CHECK ON THE OPTION “VERIFY AFTER PROGRAMMING” AND CLICK ON START”