Embedded System Lecture Notes
Embedded System Lecture Notes
Embedded System Lecture Notes
EMBEDDED SYSTEMS
1
Introduction to Embedded System
Physically, embedded systems range from portable devices such as digital watches and
MP3 players, to large stationary installations like traffic lights, factory controllers, or the systems
controlling nuclear power plants. 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.
Embedded systems are designed to do some specific task, rather than be a general-
purpose computer for multiple tasks. Some also have real-time performance constraints that
must be met, for reason such as safety and usability; others may have low or no
performance requirements, allowing the system hardware to be simplified to reduce costs.
Embedded systems are not always separate devices. Most often they are physically built-in
to the devices they control
The software written for embedded systems is often called firmware, and is stored in read-
only memory or Flash memory chips rather than a disk drive. It often runs with limited
hardware resources: small or no keyboard, screen, and little memory.
CPU platforms
Embedded processors can be broken into two broad categories: microprocessors (μP)
and microcontrollers (μC), which have many more peripherals on chip, reducing cost and size.
Contrasting to the personal computer and server markets, a fairly large number of basic CPU
architectures are used; there are Von Neumann as well as various degrees of Harvard
2
Embedded System
architectures, RISC as well as non-RISC; word lengths vary from 4-bit to 64-bits and beyond
(mainly in DSP processors) although the most typical remain 8/32-bit. Most architecture comes
in a large number of different variants and shapes, many of which are also manufactured by
several different companies. Some of the common architectures are: 8051, PIC, ARM, AVR,
Blackfin, 68HC11, MIPS, PowerPC, Z80, X86, SHARC, etc. A common configuration for very-
high-volume embedded systems is the system on a chip (SoC), an application-specific
integrated circuit (ASIC), for which the CPU core was purchased and added as part of the chip
design. A related scheme is to use a field-programmable gate array (FPGA), and program it with
all the logic, including the CPU. The CPU selection for the embedded system is application
dependent. The embedded system attributes are given in Appendix A.
Peripherals
Embedded Systems talk with the outside world via peripherals, such as:
Embedded Software
3
Embedded System
Simple control loop: In this design, the software simply has a loop. The loop calls subroutines,
each of which manages a part of the hardware or software.
Interrupt controlled system: Some embedded systems are predominantly interrupt controlled.
This means that tasks performed by the system are triggered by different kinds of events
Cooperative multitasking: A non-preemptive multitasking system is very similar to the simple
control loop scheme, except that the loop is hidden in an API. The programmer defines a series
of tasks, and each task gets its own environment to "run" in. Then, when a task is idle, it calls an
idle routine
Preemptive multitasking or multi-threading: In this type of system, a low-level piece of code
switches between tasks or threads based on a timer (connected to an interrupt). This is the level
at which the system is generally considered to have an "operating system" kernel. Depending
on how much functionality is required, it introduces more or less of the complexities of managing
multiple tasks running conceptually in parallel.
4
Embedded System
Next the source code needs to be translated into instructions the microcontroller can
actually execute. A microcontroller's instruction set is represented by "opcodes". Opcodes are
unique sequence of bits ("0" and "1") that are decoded by the controller's instruction decode
logic and then executed. Instead of writing opcodes in bits, they are commonly represented as
hexadecimal numbers, whereby one hex number represents 4 bits within a byte, so it takes
eight hex numbers to represent 32 bits or 4 byte. For that reason a microcontroller's firmware in
machine-readable form is also called Hex-Code and the file that stores that code Hex-File.
Assemblers or C Compilers translate the human readable source code into "hex
code" that represents the machine instructions (opcodes).
Linkers, link code modules saved in different files together into a single final program. At
the same time they take care of a chip's memory allocation by assigning each instruction to a
microcontroller memory addresses in such a way that different modules do not overlap.
Librarians help you to manage, organize and revision control a library of re-usable code
modules.
A debugger is a piece of software running on the PC, which has to be tightly integrated
with the simulator/ emulator that you use to validate your code. A Debugger allows you to
download your code to the emulator's memory and then control all of the functions of the
emulator from a PC. Common debugging features include the capability to examine and modify
the microcontroller's on-chip registers, data- and program-memory; pausing or stopping
program executing at defined program locations by setting breakpoints; single-stepping
(execute one instruction at a time) through the code; and looking at a history of executed code
(trace).
5
Embedded System
Debugging Tools: When it comes to debugging your code and testing your application there
are several different tools you can utilize that differ greatly in terms of development time spend
and debugging features available.
Simulators: Simulators try to model the behavior of the complete microcontroller in software.
Some simulators go even a step further and include the whole system (simulation of peripherals
outside of the microcontroller). No matter how fast your PC, there is no simulator on the market
that can actually simulate a microcontroller's behavior in real-time. Simulating external events
can become a time-consuming exercise, as you have to manually create "stimulus" files that tell
the simulator what external waveforms to expect on which microcontroller pin. A simulator can
also not talk to your target system, so functions that rely on external components are difficult to
verify. For that reason simulators are best suited to test algorithms that run completely within the
microcontroller. They are the perfect tool to complement expensive emulators for large
development teams, where buying an emulator for each developer is financially not feasible.
Emulators: An emulator is a piece of hardware that ideally behaves exactly like the real
microcontroller chip with all its integrated functionality. It is the most powerful debugging tool of
all. A microcontroller's functions are emulated in real-time and non-intrusively.
In-System Programming (ISP): FLASH microcontrollers can be programmed both in-circuit (in-
system) and out-of-circuit. With in-circuit programming the microcontroller is already soldered
into the target system and can be programmed via one of its communication interfaces (UART,
SPI, USB). This requires that you have the signals required for programming routed to an in-
system-programming (ISP) connector to which an ISP programmer can be hooked up. The ISP
connector required varies from manufacturer to manufacturer and microcontroller to
microcontroller, so it is recommended that before you start your PCB layout, you decide on
which ISP programmer you want to use and find out which ISP connector is required for it. As
ISP programming is done via a serial interface it is slower than out-of-circuit programming that
uses parallel data transfers.
6
Embedded System
MICROCONTROLLERS
2
A programmable device used in majority of embedded applications is
“microcontroller”. By the mid-1980s, the most of the processor’s previously external system
components moved onto the same chip. Such integrated systems were called microcontrollers
rather than microprocessors, and widespread adoption became feasible. At such low costs per
part, it became a very attractive alternative to building dedicated logic systems. A
microcontroller is essentially a microprocessor with several other features embedded onto a
single chip. The reduced chip count, reduced power consumption and reduced design cost of
the microcontroller allows it to used in embedded applications. In fact, industry uses 10 times as
many microcontrollers as microprocessors for embedded system applications. The embedded
system is also called as microcontroller based systems. The microcontrollers used in
embedded applications which contains extra logic such as Universal Asynchronous Receiver
Transmitter (UART), PWM unit, Analog to Digital converter (ADC), Digital to Analog Converter
(DAC) and etc., to help talk to the real world is called as embedded controllers.
Types of Microcontrollers
Some of the common architectures of the CPU used in Embedded Systems are: 8051,
PIC, ARM, AVR, Blackfin, 68HC11, MIPS, PowerPC, Z80, X86, SHARC, etc. Intel Corporation
introduced the 8051 architecture, which is the new architectural challenge of microprocessors.
The microcontrollers are often called as the enhanced version of microprocessors. The 8051
architecture is the CISC (Complex Instruction Set Computer) architecture. The microcoded
instructions and large number of instructions of the CISC controllers are tending to be complex.
On the other hand the RISC (Reduced Instruction Set Computer) architecture is developed with
non-microcoded instructions and less number of instructions. But the code density will be higher
in RISC. PIC is the member of the RISC family.
7
Embedded System
Microcontroller IC Packaging
The earliest integrated circuits were
packaged in ceramic flat packs, which continued
to be used by the military for their reliability and
small size for many years. Commercial circuit
packaging quickly moved to the dual in-line
package (DIP). In the 1980s pin counts of VLSI
circuits exceeded the practical limit for DIP
packaging, leading to pin grid array (PGA) and
leadless chip carrier (LCC) package & after that
Small-Outline Integrated Circuit (SOIC) and PLCC
packages. In the late 1990s, PQFP and TSOP
packages became the most common for high pin
count devices. Intel and AMD are currently
transitioning from PGA packages on high-end
microprocessors to land grid array (LGA)
packages.
Fig. 2.2: IC Packages
8
Embedded System
ARM ARCHITECTURE
3
The ARM (Advanced RISC Machine) architecture is a 32-bit RISC processor
architecture developed by ARM Limited, that is widely used in a number of embedded designs.
Because of their power saving features, ARM CPUs are dominant in the mobile electronics
market, where low power consumption is a critical design goal. Today, the ARM family accounts
for approximately 75% of all embedded 32-bit RISC CPUs, making it one of the most widely
used 32-bit architectures in the world. ARM CPUs are found in all corners of consumer
electronics, from portable devices to computer peripherals. The following figure shows the 32-
bit microcontroller growth.
Why ARM?
The use of RISC processors over CISC processors in embedded systems today is wide
spread and seems to be the trend of the future. This is because when it comes to embedded
systems, RISC has many advantages over CISC both in hardware and software implementation
of these embedded systems. Some of these benefits of RISC are:
Even though RISC is more appropriate for embedded applications it has the following
limitations.
RISCs generally have poor code density compared with CISCs
Poor code density leads to higher memory power consumption (For fetching)
9
Embedded System
ARM architecture is developed to utilize the benefits of CISC and RISC by improving
the code density and reducing the power consumption. ARM Limited has incorporated a
novel mechanism, called the Thumb architecture. The Thumb instruction set is a 16-bit
compressed form of the original 32-bit ARM instruction set, and employs dynamic
decompression hardware in the instruction pipeline. The ARM architecture is based on Reduced
Instruction Set Computer (RISC) principles. The RISC instruction set and related decode
mechanism are much simpler than those of CISC designs.
(Note: At this point, you may ask why have two instruction sets in the same CPU? But really the
ARM contains only one instruction set: the 32-bit set. When it's operating in the Thumb state,
the processor simply expands the smaller shorthand instructions fetched from memory into their
32-bit equivalents. The difference between two equivalent instructions lies in how the
instructions are fetched and interpreted prior to execution, not in how they function. Since the
expansion from 16-bit to 32-bit instruction is accomplished via dedicated hardware within the
chip, it doesn't slow execution even a bit. But the narrower 16-bit instructions do offer memory
advantages.)
ARM architecture has a unique combination of features that makes ARM very popular
embedded architecture today:
ARM History
The first ARM processor was developed at Acorn Computers Limited, of Cambridge,
England, between October 1983 and April 1985. At that time, and until the formation of
Advanced RISC Machines Limited (which later was renamed simply ARM Limited) in 1990,
ARM stood for Acorn RISC Machine. During this time Acorn was one of the leading names in
the British personal computer market. Other significant players were Sinclair, another
Cambridge start-up, and to a lesser extent the American companies Apple, Commodore and
Tandy, along with a host of smaller British developers producing a wide range of machines
targeted at the booming home computer market. Acorn's initial success was sealed when the
British Broadcasting Corporation (BBC) commissioned a new home computer model from the
company to be sold as the BBC Microcomputer, to tie in with a public computer education
program shown on BBC television in the UK.
The release of the BBC Micro in 1982 caught the crest of the home computer wave in
Britain, and the BBC name gave Acorn's design added credibility compared with competing
machines from the many other developers in this market. Sales exceeded all expectations:
10
Embedded System
original estimates by the BBC and Acorn were that at best tens of thousands of units would be
sold. In fact, to date nearly two million BBC Micro-compatible computers have been sold by
Acorn, and it quickly grew from a small company with tens of staff into a medium-sized company
employing hundreds with an annual turnover of tens of millions of pounds.
The BBC Micro was based around the 8-bit 6502 processor from Rockwell, the same
chip that powered the Apple II. Initial models featured color graphics and 32 KB of RAM. Data
was stored on audio-cassettes; hard and floppy disk drive interfaces were also available, and
Acorn was an early proponent of local area networking with its Econet system. Another
important feature of the BBC Micro was its capacity to accept a second processor attached via
an expansion port known as the Tube. Connectivity, interoperability and networking were
familiar concepts to many BBC Micro users long before they were established in the rest of the
personal computer world, via such options as the Tube. This required a degree of
interoperability between host and second processor, as well as Acorn's Econet local area
networking standard.
Acorn was to continue to release 6502-based variants of the BBC Micro for four more
years. Production of the most successful model, the Master, only ceased in May 1993, and
these computers form the backbone of computing provision in many British schools. However it
was clear to the advanced research and development team that there was no clear step forward
to the next generation of processors, no obvious 16-bit processor to use in future Acorn
systems. One Acorn model, the Communicator, used a 16-bit 6502 derivative, the 65C816
processor, the same device as used in the Apple IIGS, but Acorn's designers were not
convinced that this chip represented the advance they were looking for. The team tried all of the
16- and 32-bit processors then on the market but found none to be satisfactory for their
purposes; in particular, the data bandwidth was not sufficiently greater than that offered by the
6502 to justify basing the next generation of Acorn computers upon them. Processors were
tested by building BBC Micro `second processor' units based upon them, and it became clear
that no chip would be found to fit the very precise requirements on which the Acorn design team
had settled.
Acorn's aim at that time was to produce personal computers, which met the needs of the
business community by providing office automation facilities. Clearly, more power was needed
than was offered by the 6502. In the fine tradition of the computer hobbyist, the design team
decided to develop their own processor, which would provide an environment with some
similarities to the familiar 6502 instruction set but lead Acorn and its products directly into the
world of 32-bit computing. Acorn has always been renowned for the caliber of its research and
development staff. It was able to pick the cream of graduates from Cambridge University, home
of a highly regarded computer science faculty, as well as attracting staff from around the world.
To them, designing a processor from scratch to meet their carefully specified criteria was an
obvious thing to do. Acorn's phenomenal success with its 8-bit computers had created a
research and development environment where staff could afford to pursue advanced projects,
which would not necessarily result in immediately saleable products, and were actively
encouraged to do so.
Work on the development of what was to become the ARM began in 1983. Working
samples were received in 1985. The team developing it included Steve Furber and Roger
Wilson, both of who had worked on the design of the BBC Micro, as well as Robert Heaton who
led the VLSI design group within Acorn. The design team worked in secret to create a chip,
which met their requirements. As described earlier, these were for a processor, which retained
the ethos of the 6502 but in a 32-bit RISC environment, and implemented this in a small device,
11
Embedded System
which it would be possible to design and test easily, and to fabricate cheaply. First the
instruction set was specified by Wilson, based on his knowledge gained as the author of much
of the original software for the BBC Micro, including its BASIC interpreter. The important initial
decisions were to use a fixed instruction length and a load/store model. Other design decisions
were taken on an instruction-by-instruction basis.
The first ARM processor, ARM1, yielded working silicon the first time it was fabricated, in
April 1985 at VLSI Technology. It bettered the stated design goals while using fewer than 25000
transistors. There was a great deal of excitement at and confidence in the new chip. The ARM
was used internally at Acorn and by Acorn developers when it was made available as a second
processor add-on for the BBC Micro; this device used the ARM1 as an additional coprocessor
and accelerator for the 6502-based BBC micro. In fact, this second processor was used to
improve the performance of the simulation tools the team had designed to finish the support
chips and also to develop the next ARM processor. The second processor add-on also enabled
third-party developers to start working with the processor and contemplating the development of
software to exploit its advanced features. The purpose of releasing the second processor was to
ensure that when a complete ARM-based system was released, potential users and developers
had some experience of ARM and were not deterred from developing application software for it
by the novelty of the technology and the lack of wide support for it in the market.
The experience of designing ARM1, and of programming the sample chips, showed that
there was some areas where the instruction set could be improved in order to maximize the
performance of systems based around it. In particular, the Multiply and Multiply and Accumulate
instructions were added in order to improve performance by eliminating the use of slow
subroutines for this purpose. Without this addition, the ARM could have been `horribly slow' in
some circumstances, according to Furber. This addition would facilitate real-time digital signal
processing, which was to be used to generate sounds, an important feature of home and
educational computers.
Although the ARM processor had been designed with the clear intention that it was to
power the next generation of Acorn personal computers, and it was equally clear that such
machines needed to be developed quickly, the design and production of ARM-based systems
by Acorn was to be more fraught than the design of the chips themselves. It was to take more
than two years from the arrival of working ARM silicon to the launch and shipment of a complete
ARM-based system. Deep within the advanced research and development labs in Cambridge,
and at the research lab that Acorn had established in Palo Alto, California, Acorn staffs were
also designing an office automation system using the ARM processor. This system was a long-
term goal of Acorn's co-founder, Dr Hermann Hauser.
By 1990 it was clear that although Acorn's financial position had stabilized, an in-house
processor design team was an expensive luxury for a small company to support. The ARM
development team had now produced a static version of the processor, the ARM2aS, making it
even more attractive to potential third-party customers. This new variant added low power
consumption to the list of features, which made the ARM attractive to developers interested in
designing low-cost portable and hand-held devices and electronic personal organizers. It was
intended for inclusion in a hand-held personal electronic organizer and communications device,
which although developed as far as working prototypes was never actually marketed. Interest in
the ARM family was growing as more designers became interested in RISC and the ARM's
design was seen to match a definite need for high-performance, low power consumption, low-
12
Embedded System
cost RISC processors. In conditions of greatest secrecy an agreement was reached between
Acorn, VLSI Technology Inc. and a company, which had expressed an interest in the ARM for
some time now, Apple. A new company was set up with Apple, Acorn and VLSI Technology as
founding partners. The Acorn RISC Machine became the Advanced RISC Machine and
Advanced RISC Machines Ltd was born. Many of the original designers moved from Acorn to
join the new company, with others working in an advisory role. Additional expertise was
provided by Apple and new blood was recruited from around the world. ARM Ltd was founded
with a clear mission to continue the development of the ARM processor and to facilitate its use
by system developers, whether as a standalone processor or as a macrocell with custom logic
or other ARM components added to it to make a custom chip.
ARM7TDMI;
ARM v4T Thumb
ARM9T
13
Embedded System
ARM Nomenclature
ARM {x}{y}{z}{T}{D}{M}{I}{E}{J}{F}{S},
Where,
x – Family
y – Memory management/protection unit (MMU)
z – Cache
T – Thumb 16-bit decoder
D – JTAG debug
M – Fast multiplier
I – Embedded ICE macrocell
E – Enhanced DSP instructions
J – Jazelle (Java Byte code Instruction)
F – Vector floating-point unit
S – Synthesizable version
Examples:
ARM7TMI (7-family, T-Thumb, D – JTAG Debug, M – Fast Multiplier, I – Embedded ICE)
ARM720T (7-family, 2-MMU, 0-8Kb cache memory)
ARM9EJ-S (9-family, E-Enhanced, J-Jazalle, S-Synthesizable)
ARM Extensions
Thumb: The recent ARM processors have a 16-bit instruction mode, called Thumb. This is
intended to allow smaller code where possible. T (Thumb)-extension shrinks the ARM
instruction set to 16-bit word length, saving about 35-40% in amount of memory compared to
32.bit instruction set. For this extension a special decoder, with Thumb instructions
decompressor and multiplexers, is used in the processors pipeline.
Jazelle: Jazelle = Java byte-code execution extension, in practice adds third instruction set to
an ARM-processor core. Jazelle is a hardware implementation of the Java virtual machine that
allows ARM processors to execute Java byte-code.
Thumb-2: Thumb-2 technology was introduced in 2003. Thumb-2 extends the limited 16-bit
instruction set of Thumb with additional 32-bit instructions. ARM and thumb code each execute
in own processor state. Thumb-2 core technology adds a mixed mode capability, defining a new
set of 32-bit instructions that execute alongside traditional 16-bit instructions in Thumb state.
14
Embedded System
Vector Floating Point (VFP): Vector Floating Point (VFP) coprocessor support is an
architecture option. The VFP architecture supports single and double precision floating-point
arithmetic, and is fully IEEE 754 compliant.
NEON: NEON media accelerating technology is a combined 64- and 128-bit SIMD (Single
Instruction Multiple Data) instruction set that provides standardized acceleration for media and
signal processing applications. NEON can execute MP3 audio decoder in less than 10 MHz.
NEON supports 8-, 16-, 32- and 64-bit integer and single precision floating-point data and
operates in SIMD operations for handling audio/video processing as well as graphics and
gaming processing.
ARM TrustZone: The TrustZone extensions provide hardware support for two separate
address spaces, such that code executing in the non-secure world cannot gain access to any
address space marked as secure.
Debug and Trace: ARM's debug and trace tools enable system developers to quickly debug
real-time software, and to trace instruction execution and associated program data at full core
speed.
AMBA: The AMBA (Advanced Microcontroller Bus Architecture) on-chip bus is an open
specification that serves as a framework for SoC designs and IP library development. The first
AMBA buses introduced were the ARM System Bus (ASB) and the ARM Peripheral Bus (APS).
Later ARM introduced another bus design the ARM Advanced High-performance Bus (AHB).
AHB provides higher data throughput than ASB because it is based on a centralized multiplexed
bus. ARM uses two versions of the AHB bus: Multi-layer AHB and AHB-Lite (it is a subset of
AHB bus which is limited to a single bus master).
ARM Intelligent Energy Manager: ARM Intelligent Energy Manager (IEM) technology
implements advanced algorithms to optimally balance processor workload and energy
consumption.
15
Embedded System
support for saturating addition and subtraction operations and 16-bit multiplication. In the sixth
version of ARM architecture, DSP support evolved into the SIMD instruction set extension.
ARM Manufacturers
LPC211x, LPC212X,
NXP LPC219X, LPC22XX,
LPC23XX, LPC24XX
AT76C110,
Atmel AT91SC321RC,
AT91SAM
Analog AD20MSP430, AD6522,
Devices AD6526, AD6528
16
Embedded System
The ARM7 core family is a 32-bit RISC CPU core optimized for cost and power
sensitive applications. Offering up to 130 MIPS (Dhrystone 2.1) the ARM 7 family incorporates
the Thumb 16-bit instruction set (enabling 32-bit performance at 8/16-bit system cost). The
ARM7 family also includes the ARM7TDMI, ARM7TDMI-S and ARM7EJ-S processor cores and
the ARM720T cached processor macrocell (for use in customer specific integrated circuits).
Of all the members of the ARM7 family the ARM7TDMI core is a 32-bit embedded RISC
processor delivered as a hard macrocell optimized to provide the best combination of
performance, power and area characteristics. The ARM7TDMI core enables system designers
to build embedded devices requiring small size, low power and high performance. The benefits
of ARM7TDMI core are listed below.
17
Embedded System
32/16-bit RISC architecture (unified bus interface, 32-bit data bus carries both
instructions and data)
32-bit ARM instruction set for maximum performance and flexibility
16-bit Thumb instruction set for increased code density
Virtual memory system support
Three stage pipeline, fast interrupt response
32-bit ALU; 37 pieces of 32-bit integer registers; 8/16/32-bit data types
Small die size and low power consumption
Seven modes of operation
User – normal program execution state
FIQ – data transfer state (DMA-type transfer)
IRQ – used for general interrupt services
Supervisor – protected mode for operating system support
Abort mode – selected when data or instruction fetch is aborted
System – operating system “privilege”-mode for user
Undefined – selected when undefined instruction is fetched
Fully static operation
Coprocessor interface
Up to 16 coprocessors can be connected to an ARM7TDMI system
Extensive debug facilities
Embedded real-time debug unit
JTAG interface unit
Interface for direct connection to Embedded Trace Macrocell (ETM).
Wide operating system and RTOS support (Eg: Windows CE, Palm OS, Linux,COS-II);
High code density, comparable to 16-bit microcontroller;
Availability in 0.25m, 0.18m and 0.1m processes;
Migration and support across new process technologies;
Code is forward-compatible to ARM9, ARM9E and ARM10 processors;
Performance: 0.9 MIPS/MHz. (ARM7TDMI);
Typical power consumption (ARM7TDMI):
at 0.25m <0.80 mW/MHz;
at 0.10m <0.25 mW/MHz.
Registers
ARM processors have 37 registers. The registers are arranged in partially overlapping
banks. The banked registers give rapid context switching. There is a different register bank for
each processor mode.
1. 30 general-purpose, 32-bit registers (GPR)
2. The program counter (PC)
3. The Current Program Status Register (CPSR)
4. Five Saved Program Status Registers (SPSR).
The general-purpose registers R0 to R15 can be split into three groups. These groups differ in
the way they are banked and in their special-purpose uses: The unbanked registers, R0 to R7,
The banked registers, R8 to R14 and Register 15, the program counter (PC).
18
Embedded System
Processor Modes
19
Embedded System
User Mode: Application programs typically run in the User mode. This is a non-privileged mode,
which restricts application programs from accessing protected resources. Furthermore, an
exception is generated if a mode switch is attempted.
System Mode: The System mode has access to the same set of registers as the User mode;
however, because this is a privileged mode, the User mode restrictions are not applicable. This
mode is used by the operating system.
Exception Mode: The Exception modes are entered when a specific exception occurs.
Supervisory Mode (svc): The reset and software interrupts are executed under the Supervisor
mode.
Fast Interrupt Mode (FIQ): When a Fast Interrupt request is externally asserted on the FIQ pin
of the processor, an FIQ exception is generated. In response to the exception, the processor
enters the Fast Interrupt mode. This mode is typically used for DMA-type data transfers.
Interrupt Mode (IRQ): When a lesser priority interrupt request is asserted on the IRQ pin, the
processor enters the IRQ mode. This mode is used for general interrupt processing.
Undefined Mode (UND): The Undefined mode is entered when an undefined exception is
generated. This exception occurs if an attempt is made to execute an undefined instruction.
Abort Mode (ABT): The Abort mode is entered when a prefetch abort or a data abort exception
occurs.
In User mode, R14 is used as a link register (LR) to store the return address when a
subroutine call is made. Register R14 can also be used as a general-purpose register if the
return address is stored on the stack. In the exception handling modes, R14 holds the return
address for the exception, or a subroutine return address if subroutine calls are executed within
an exception. Register R14 can be used as a general-purpose register if the return address is
stored on the stack. The program counter (PC) is accessed as R15. It is incremented by one
word (four bytes) for each instruction in ARM state, or by two bytes in Thumb state. During
execution, R15 does not contain the address of the currently executing instruction. The address
of the currently executing instruction is typically (PC–8) for ARM, or (PC–4) for Thumb.
20
Embedded System
The N, Z, C, and V bits are the condition code flag that can set these bits by arithmetic
and logical operations. The ARM7TDMI-S tests these flags to determine whether to execute an
instruction. All instructions can execute conditionally in ARM state. In Thumb state, only the
Branch instruction can be executed conditionally.
ARM employs a load-store architecture. This means that the instruction set will only
process values which are in registers, and will always place the result of such processing into a
register. The only operations, which apply to memory, are ones which copy memory values into
registers (load instructions) or copy register values into memory (store instructions). CISC
processors typically allow a value from memory to be added to a value in a register, and
sometimes allow a value in a register to be added to a value in memory. ARM does not support
21
Embedded System
such memory-to-memory operations. All ARM instructions fall into one of the following 3
categories.
— The ARM handles I/O peripherals as memory-mapped devices with interrupt support.
— The internal registers in these devices appear as addressable locations within the ARM’s
memory map and may be read and write using the same (load-store) instructions as any
other memory locations.
— Peripherals may attract the processor attention by making an interrupt request using either
the normal interrupt (IRQ) or the fast interrupt (FIQ) input. Both interrupt inputs are level-
sensitive and maskable. Normally most interrupt sources share the IRQ input, with just one
or two time-critical sources connected to the higher-priority FIQ input.
— Some systems may include direct memory access (DMA) hardware external to the processor
to handle high-bandwidth I/O traffic.
— Interrupts are a form of exception and are handled as outlined below.
ARM Exceptions
The ARM architecture supports a range of interrupts, traps and supervisor calls, all
grouped under the general heading of exceptions. The general way these are handled is the
same in all cases:
1. The current state is saved by copying the PC into r14_exc and the CPSR into SPSR_exc
(where _exc stands for the exception type).
2. The processor operating mode is changed to the appropriate exception mode.
3. The PC is forced to a particular value depending on the type of exception.
4. The instruction at the location the PC is forced to (the vector address) will usually contain a
branch to the exception handler. The exception handler will use r13_exc, which will normally
have been initialized to point to a dedicated stack in memory; to save some user registers for
use as work registers.
5. The return to the user program is achieved by restoring the user registers and then using an
instruction to restore the PC and the CPSR. (This may involve some adjustment of the PC value
saved in r14_exc to compensate for the state of the pipeline when the exception arose.
22
Embedded System
Pipelining
3-Stage
Pipelining
23
Embedded System
LPC2148 MICROCONTROLLER
5
The LPC2148 microcontroller is based on a 16-bit/32-bit ARM7TDMI-S CPU with real-
time emulation and embedded trace support that combine microcontroller with embedded high-
speed flash memory of 512 KB manufactured by NXP (Founded by Philips). A 128-bit wide
memory interface and unique accelerator architecture enable 32-bit code execution at the
maximum clock rate. For critical code size applications, the alternative 16-bit Thumb mode
reduces code by more than 30 % with minimal performance penalty. Due to their tiny size and
low power consumption, LPC2148 microcontroller is ideal for applications where miniaturization
is a key requirement, such as access control and point-of-sale. Serial communications
interfaces ranging from a USB 2.0 Full-speed device, multiple UARTs, SPI, SSP to I2C-bus and
on-chip SRAM of 40 kB, make these devices very well suited for communication gateways and
protocol converters, soft modems, voice recognition and low end imaging, providing both large
buffer size and high processing power. Various 32-bit timers, single or dual 10-bit ADC(s), 10-bit
DAC, PWM channels and 45 fast GPIO lines with up to nine edge or level sensitive external
interrupt pins make these microcontrollers suitable for industrial control and medical systems.
Key Features:
• 32-Bit ARM7® Core Architecture
• Full-Speed USB 2.0 Device
• Very Fast On-Chip Flash Up to 512KB
• Up to 40KB SRAM
• 45 Fast I/O Pins with Up to 15MHz Switching
• Vectored Interrupt Controller (VIC)
• 3.3V / 60MHz Operation
• In-System Programming (ISP) via on-chip boot
loader software
• Two 10-bit ADCs provide a total of 14 analog
inputs
• Single 10-bit DAC provides variable analog
output
• Multiple serial interfaces - Two UARTs, Two
Fast I2C-bus (400 Kbit/s), SPI and SSP
24
Embedded System
Pin Description:
25
Embedded System
RTXC1
D+ 10 SB bi-directional D+ line
26
Embedded System
3.3 V power supply: This is the power supply voltage for the
VDD 23
core and I/O ports.
27
Embedded System
28
Embedded System
29
Embedded System
VBAT RTC power supply voltage: 3.3 V on this pin supplies the
49
power to the RTC
30
Embedded System
3.3 V power supply: This is the power supply voltage for the core
VDD 51
and I/O ports
31
Embedded System
XTAL1 62 Input to the oscillator circuit and internal clock generator circuits
LPC2148 Architecture
On-Chip Flash Memory: The LPC2148 incorporate 512 kB flash memory system. This memory
may be used for both code and data storage. Programming of the flash memory may be
accomplished in several ways. It may be programmed In System via the serial port. The
application program may also erase and/or program the flash while the application is running,
allowing a great degree of flexibility for data storage field firmware upgrades, etc. Due to the
architectural solution chosen for an on-chip boot loader, flash memory available for user’s code
on 500 kB. The LPC2148 flash memory provides a minimum of 100000 erase/write cycles and
20 years of data-retention.
32
Embedded System
On-chip Static RAM: On-chip static RAM may be used for code and/or data storage. The
SRAM may be accessed as 8-bit, 16-bit, and 32-bit. The LPC2148 provide 32 kB of static RAM.
Also an 8 kB SRAM block intended to be utilized mainly by the USB can also be used as a
general purpose RAM for data storage and code storage and execution.
General purpose parallel I/O (GPIO): Device pins that are not connected to a specific
peripheral function are controlled by the GPIO registers. Pins may be dynamically configured as
inputs or outputs. Separate registers allow setting or clearing any number of outputs
simultaneously. The value of the output register may be read back, as well as the current state
of the port pins.
33
Embedded System
Vectored Interrupt controller: The Vectored Interrupt Controller (VIC) accepts all of the
interrupt request inputs and categorizes them as Fast Interrupt Request (FIQ), vectored
Interrupt Request (IRQ), and non-vectored IRQ as defined by programmable settings. The
programmable assignment scheme means that priorities of interrupts from the various
peripherals can be dynamically assigned and adjusted. Fast interrupt request (FIQ) has the
highest priority. Vectored IRQs have the middle priority. Non-vectored IRQs have the lowest
priority.
External interrupt inputs: The LPC2148 include up to nine edge or level sensitive External
Interrupt Inputs as selectable pin functions. When the pins are combined, external events can
be processed as four independent interrupt signals. The External Interrupt Inputs can optionally
be used to wake-up the processor from Power-down mode. Additionally capture input pins can
also be used as external interrupts without the option to wake the device up from Power-down
mode.
UARTs: The LPC2148 contains two UARTs. In addition to standard transmit and receive data
lines, the LPC2148 UART1 also provides a full modem control handshake interface. Compared
to previous LPC2000 microcontrollers, UARTs in LPC2148 introduce a fractional baud rate
generator for both UARTs, enabling these microcontrollers to achieve standard baud rates such
as 115200 with any crystal frequency above 2 MHz. In addition, auto-CTS/RTS flow-control
functions are fully implemented in hardware (UART1).
34
Embedded System
I2C-bus serial I/O controller: The LPC2148 contains two I2C-bus controllers. The I2C-bus is bi-
directional, for inter-IC control using only two wires: a serial clock line (SCL), and a serial data
line (SDA). Each device is recognized by a unique address and can operate as either a
receiver-only device. Transmitters and/or receivers can operate in either master or slave mode,
depending on whether the chip has to initiate a data transfer or is only addressed. The I 2C-bus
is a multi-master bus; it can be controlled by more than one bus master connected to it. The I 2C-
bus implemented in LPC2148 supports bit rates up to 400 kbit/s (Fast I2C-bus).
SPI serial I/O controller: The LPC2148 contains one SPI controller. The SPI is a full duplex
serial interface, designed to handle multiple masters and slaves connected to a given bus. Only
a single master and a single slave can communicate on the interface during a given data
transfer. During a data transfer the master always sends a byte of data to the slave, and the
slave always sends a byte of data to the master.
SSP serial I/O controller: The LPC2148 contains one SSP. The SSP controller is capable of
operation on a SPI, 4-wire SSI, or Micro-wire bus. It can interact with multiple masters and
slaves on the bus. However, only a single master and a single slave can communicate on the
bus during a given data transfer. The SSP supports full duplex transfers, with data frames of 4
bits to 16 bits of data flowing from the master to the slave and from the slave to the master.
Often only one of these data flows carries meaningful data.
Compatible with Motorola’s SPI, TI’s 4-wire SSI and National Semiconductor’s Micro-
wire buses.
Synchronous serial communication
35
Embedded System
10-bit ADC: The LPC2148 contains two analog to digital converters. These converters are
single 10-bit successive approximation analog to digital converters. While ADC0 has six
channels, ADC1 has eight channels. Therefore, total numbers of available ADC inputs are 14.
10-bit DAC: The DAC enables the LPC2148 to generate a variable analog output. The
maximum DAC output voltage is the VREF voltage.
10-bit DAC
Buffered output
Power-down mode available
Selectable speed versus power
USB 2.0 device controller: The USB is a 4-wire serial bus that supports communication
between a host and a number (127 max) of peripherals. The host controller allocates the USB
bandwidth to attached devices through a token-based protocol. The bus supports hot plugging,
unplugging, and dynamic configuration of the devices. All transactions are initiated by the host
controller. The LPC2148 is equipped with a USB device controller that enables 12 Mbit/s data
exchange with a USB host controller. It consists of a register interface, serial interface engine,
endpoint buffer memory and DMA controller. The serial interface engine decodes the USB data
stream and writes data to the appropriate end point buffer memory. The status of a completed
USB transfer or error condition is indicated via status registers. An interrupt is also generated if
enabled. A DMA controller can transfer data between an endpoint buffer and the USB RAM.
Watchdog timer: 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
36
Embedded System
generate a system reset if the user program fails to ‘feed’ (or reload) the watchdog within a
predetermined amount of time.
Real-time clock: The RTC is designed to provide a set of counters to measure time when
normal or idle operating mode is selected. The RTC has been designed to use little power,
making it suitable for battery-powered systems where the CPU is not running continuously (Idle
mode).
Pulse width modulator: The PWM is based on the standard timer block and inherits all of its
features, although only the PWM function is pinned out on the LPC2148. The timer is designed
to count cycles of the peripheral clock (PCLK) and optionally generate interrupts or perform
other actions when specified timer values occur, based on seven match registers. The PWM
function is also based on match register events.
Crystal oscillator: On-chip integrated oscillator operates with external crystal in range of 1
MHz to 25 MHz. The oscillator output frequency is called fosc and the ARM processor clock
frequency is referred to as CCLK for purposes of rate equations, etc. fosc
and CCLK are the same value unless the PLL is running and connected.
PLL: The PLL accepts an input clock frequency in the range of 10 MHz to 25 MHz. The input
frequency is multiplied up into the range of 10 MHz to 60 MHz with a Current Controlled
Oscillator (CCO). The multiplier can be an integer value from 1 to 32 (in practice, the multiplier
value cannot be higher than 6 on this family of microcontrollers due to the upper frequency limit
of the CPU). The CCO operates in the range of 156 MHz to 320 MHz, so there is an additional
divider in the loop to keep the CCO within its frequency range while the PLL is providing the
desired output frequency. The output divider may be set to divide by 2, 4, 8, or 16 to produce
the output clock. Since the minimum output divider value is 2, it is insured that the PLL output
has a 50 % duty cycle. The PLL is turned off and bypassed following a chip reset and may be
enabled by software. The program must configure and activate the PLL, wait for the PLL to
Lock, then connect to the PLL as a clock source. The PLL settling time is 100 ms.
37
Embedded System
Reset and wake-up timer: Reset has two sources on the LPC2148: the RESET pin and
watchdog reset. The RESET pin is a Schmitt trigger input pin with an additional glitch filter.
Assertion of chip reset by any source starts the Wake-up Timer, causing the internal chip reset
to remain asserted until the external reset is de-asserted, the oscillator is running, a fixed
number of clocks have passed, and the on-chip flash controller has completed its initialization.
When the internal reset is removed, the processor begins executing at address 0, which is the
reset vector. At that point, all of the processor and peripheral registers have been initialized to
predetermined values. The Wake-up Timer ensures that the oscillator and other analog
functions required for chip operation are fully functional before the processor is allowed to
execute instructions. This is important at power on, all types of reset, and whenever any of the
aforementioned functions are turned off for any reason. Since the oscillator and other functions
are turned off during Power-down mode, any wake-up of the processor from Power-down mode
makes use of the Wake-up Timer.
The Wake-up Timer monitors the crystal oscillator as the means of checking whether it is
safe to begin code execution. When power is applied to the chip, or some event caused the chip
to exit Power-down mode, some time is required for the oscillator to produce a signal of
sufficient amplitude to drive the clock logic.
Brownout detector: The LPC2148 include 2-stage monitoring of the voltage on the VDD pins.
If this voltage falls below 2.9 V, the BOD asserts an interrupt signal to the VIC. This signal can
be enabled for interrupt; if not, software can monitor the signal by reading dedicated register.
The second stage of low voltage detection asserts reset to inactivate the LPC2148 when the
voltage on the VDD pins falls below 2.6 V. This reset prevents alteration of the flash as
operation of the various elements of the chip would otherwise become unreliable due to low
voltage. The BOD circuit maintains this reset down below 1 V, at which point the POR circuitry
maintains the overall reset. Both the 2.9 V and 2.6 V thresholds include some hysteresis. In
normal operation, this hysteresis allows the 2.9V detection to reliably interrupt, or a regularly
executed event loop to sense the condition.
VPB (VLSI Peripheral bus): The VPB divider determines the relationship between the
processor clock (CCLK) and the clock used by peripheral devices (PCLK). The VPB divider
serves two purposes. The first is to provide peripherals with the desired PCLK via VPB bus so
that they can operate at the speed chosen for the ARM processor. In order to achieve this, the
VPB bus may be slowed down to 1/2 to 1/4 of the processor clock rate. The second purpose of
the VPB divider is to allow power savings when an application does not require any peripherals
to run at the full processor rate. Because the VPB divider is connected to the PLL output, the
PLL remains active (if it was running) during Idle mode.
AHB (Advanced High-performance Bus): AHB is a bus protocol published by ARM Ltd.
Company. In addition to previous release, it has the following features:
Single edge clock protocol
Split transactions
Several bus masters & Pipelined operations
Single-cycle bus master handover
Non-tristate implementation
Large bus-widths (64/128 bit)
A simple transaction on the AHB consists of an address phase and a subsequent data
phase (without wait states: only two bus-cycles). Access to the target device is controlled
through a MUX (non-tristate), thereby admitting bus-access to one bus-master at a time.
38
Embedded System
MEMORY ORGANIZATION
6
Memory is the most important unit in the computing system to store, retain and retrieve
the information of the processes. Two basic types of memory are ROM (Read Only Memory)
and RAM (Random Access Memory). Information stored in ROM cannot be modified (at least
not very quickly or easily). The values stored in ROM are always there, whether the power is on
or not. ROM is most commonly used to store system-level programs that we want to have
available at all times. The word RAM is mostly associated with volatile types of memory, where
the information is lost after the power is switched off. Obviously, RAM needs to be writeable in
order for it to do its job of holding programs and data that you are working on. The volatility of
RAM also means that you risk losing what you are working on unless you save it frequently.
RAM is much faster than ROM is, due to the nature of how it stores information. The memories
commonly used are described below.
Memory Types
ROM: ROM is a type of memory that does not lose its contents when the power is turned off.
For this reason, ROM is also called nonvolatile memory. There are different types of ROM, such
as PROM, EPROM, EEPROM, OTP ROM, and FLASH EEPROM.
EPROM: In EPROM, one can program the memory chip and erase it thousands of times. This is
especially necessary during the development of the prototype of an embedded systems based
design. A widely used EPROM is called UV-EPROM where UV stands for ultra-violet. All UV-
EPROM chips have a window that is used to shine UV radiation to erase its contents. The main
problem, and indeed the major disadvantage of UV-EPROM is that it cannot be programmed
while in the system board. To find a solution, EEPROM was invented.
EEPROM: The most important characteristic of this memory is that it does not lose its contents
with the loss of power supply. In this type the data can be erased electrically, using voltage,
which the system operates on. Data can be retained in EEPROM without power supply for up to
many years. In practice, EEPROM memory is used for storing important data or process
parameters.
Flash Memory: Flash EEPROM has become a popular user programmable memory chip since
the early 90s. It is also electrically erasable, but the number of cycles of writing and erasing is
less when compared to EEPROM. In this the process of erasure of the entire contents takes
less than a second, or one might say in a flash, hence its name flash EEPROM. Flash
memories increases the performance of the computer, since flash memory is semiconductor
memory with access time in the range of 100 ns compared with disk access time in the range of
tens of milliseconds.
RAM: RAM memory is called volatile memory since cutting off the power to the IC will result in
the loss of data. The three types of RAM are: SRAM (static RAM), NV-RAM (non-volatile RAM),
and DRAM (dynamic RAM). Storage cells in SRAM are made up of flip-flops and therefore do
not require refreshing in order to keep their data. The problem with the use of flip-flops for
storage cells is that each cell requires at least 6 transistors to build, and the cell holds only 1 bit
of data. NV-RAM combines the best of RAM and ROM: the read and write ability of RAM, plus
the nonvolatile of ROM. DRAM uses capacitors as storage cells. The major advantages of
39
Embedded System
DRAM are high density (capacity), cheaper cost per bit, and lower power consumption per bit.
The disadvantage is that it must be refreshed periodically, due to the fact that capacitor cell
loses its charge.
Memory Architecture
Von-Neumann Architecture: Von Neumann architectures are computer architectures that use
the same storage device for both instructions and data. By treating the instructions in the same
way as the data, the machine could easily change the instructions. In other words the machine
was reprogrammable. Because the machine did not distinguish between instructions and data, it
allowed a program to modify or replicate a program.
Address Bus
MEMORY
CPU Data Bus PROGRAM &
DATA
The Harvard architecture executes instructions in fewer instruction cycles than the Von
Neumann architecture. This is because a much greater amount of instruction parallelism is
possible in the Harvard architecture. Parallelism means that fetches for the next instruction can
take place during the execution of the current instruction, without having to either wait for a
"dead" cycle of the instruction's execution or stop the processor's operation while the next
instruction is being fetched.
ARM memory may be viewed as a linear array of bytes numbered from zero up to 2 32-1
(byte-addresses memory). Data items may be 8-bit bytes, 16-bit half-words or 32-bit words.
40
Embedded System
Words are always aligned on 4-byte boundaries (that is, the two least significant address bits
are zero). Half-words are aligned on even byte boundaries.
41
Embedded System
The ARM7TDMI-S has Von Neumann architecture, with a single 32-bit data bus carrying
both instructions and data. Only load, store, and swap instructions can access data from
memory. Data can be 8-bit bytes, 16-bit halfwords, or 32-bit words. Words must be aligned to 4-
byte boundaries. Halfwords must be aligned to 2-byte boundaries. The LPC2148 incorporates
several distinct memory regions, shown above. The basic concept on the LPC2148 is that each
memory area has a "natural" location in the memory map. This is the address range for which
code residing in that area is written. The bulk of each memory space remains permanently fixed
in the same location, eliminating the need to have portions of the code designed to run in
different address ranges. Because of the location of the interrupt vectors on the ARM7
processor (at addresses 0x0000 0000 through 0x0000 001C,, a small portion of the Boot Block
and SRAM spaces need to be re-mapped in order to allow alternative uses of interrupts in the
different operating modes.
Both the AHB and VPB peripheral areas are 2-megabyte spaces, which are divided up
into 128 peripherals. Each peripheral space is 16 kilobytes in size. This allows simplifying the
address decoding for each peripheral. All peripheral register addresses are word aligned (to 32-
bit boundaries) regardless of their size. This eliminates the need for byte lane mapping
hardware that would be required to allow byte (8-bit) or half-word (16-bit) accesses to occur at
smaller boundaries. An implication of this is that word and half-word registers must be accessed
all at once. For example, it is not possible to read or write the upper byte of a word register
separately.
42
Embedded System
The LPC2148 incorporate a 512 kB Flash memory system. This memory may be used
for both code and data storage. Programming of the Flash memory may be accomplished in
several ways: over the serial built-in JTAG interface, using In System Programming (ISP) and
UART0, or by means of In Application Programming (IAP) capabilities. The application program,
using the IAP functions, may also erase and/or program the Flash while the application is
running, allowing a great degree of flexibility for data storage field firmware upgrades, etc. When
the LPC2148 on-chip boot loader is used, 500 kB of Flash memory is available for user code.
The LPC2148 Flash memory provides minimum of 100,000 erase/write cycles and 20 years of
data-retention.
On-chip Static RAM (SRAM) may be used for code and/or data storage. The on-chip
SRAM may be accessed as 8-bits, 16-bits, and 32-bits. The LPC2148 provide 32 kB of static
RAM. The LPC2148 SRAM is designed to be accessed as a byte-addressed memory. Word
and halfword accesses to the memory ignore the alignment of the address and access the
naturally aligned value that is addressed (so a memory access ignores address bits 0 and 1 for
word accesses, and ignores bit 0 for halfword accesses). Therefore valid reads and writes
require data accessed as halfwords to originate from addresses with address line 0 being 0
(addresses ending with 0, 2, 4, 6, 8, A, C, and E in hexadecimal notation) and data accessed as
words to originate from addresses with address lines 0 and 1 being 0 (addresses ending with 0,
4, 8, and C in hexadecimal notation). This rule applies to both off and on-chip memory usage.
The SRAM controller incorporates a write-back buffer in order to prevent CPU stalls during
back-to-back writes. The write-back buffer always holds the last data sent by software to the
SRAM. This data is only written to the SRAM when another write is requested by software (the
data is only written to the SRAM when software does another write). If a chip reset occurs,
actual SRAM contents will not reflect the most recent write request (i.e. after a "warm" chip
reset, the SRAM does not reflect the last write operation). Any software that checks SRAM
contents after reset must take this into account. Two identical writes to a location guarantee that
the data will be present after a Reset. Alternatively, a dummy write operation before entering
idle or power-down mode will similarly guarantee that the last data written will be present in
SRAM after a subsequent Reset.
43
Embedded SystemADDRESSING MODES AND INSTRUCTION SET
7
ARM instructions process data held in registers and only access memory with load and
store instructions. ARM instructions commonly take two or three operands.
Example:
ARM processor has 36 instruction formats; the instruction word length is 32-bits.
Instructions are stored word-aligned, so the least significant two bits of instruction addresses are
always zero in ARM state. Some instructions use the least significant bit to determine whether
the code being branched to is Thumb code or ARM code.
Classes of Instructions
The ARM and Thumb instruction sets can be divided into four main classes of instruction:
1. Data processing instructions
2. Load and store instructions
3. Branch instructions
4. Coprocessor instructions
Addressing Modes
In ARM state, all instructions are conditionally executed according to the state of the
CPSR condition codes and the instruction’s condition field. This field (bits 31:28) determines the
circumstances under which an instruction is to be executed. If the state of the C, N, Z and V
flags fulfill the conditions encoded by the field, the instruction is executed; otherwise it is
ignored. There are 16 possible conditions, each represented by a two-character suffix that can
be appended to the instruction’s mnemonic. For example, a Branch (B) becomes BEQ for
Branch if Equal, which means the Branch will only be taken if the Z flag is set. The condition
(1111) is reserved, and must not be used. In the absence of a suffix, the condition field of most
instructions is set to Always (AL). This means the instruction will always be executed regardless
of the CPSR condition codes.
44
Embedded System
Flags
Mnemonic Description
Affected
ADC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Add with Carry N, Z, V, C
ADD {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Add N, Z, V, C
AND {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Bit-wise AND N, Z, C
B {<cond>} <target_address>, BL {<cond>} Branch, Branch and
None
<target_address> Link
BIC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Bit Clear N, Z
Branch and
BX {<cond>} <Rm> None
Exchange
CMN {<cond>} <Rn>, <shifter_operand> Compare Negative N, Z, V, C
CMN {<cond>} <Rn>, <shifter_operand> Compare N, Z, V, C
EOR {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Bit-wise Ex - OR N, Z, C
LDM {<cond>}<addressing_mode>, <Rn>{!},
Load Multiple None
<registers>
LDR {<cond>} <Rd>, <addressing_mode> Load Register None
LDRB {<cond>} <Rd>, <addressing_mode> Load Register Byte None
Load Register
LDRH {<cond>} <Rd>, <addressing_mode> None
Halfword
LDRSB {<cond>} <Rd>, <addressing_mode> Load Register None
45
Embedded System
Signed Byte
Load Register
LDRSH {<cond>} <Rd>, <addressing_mode> None
Signed Halfword
N, Z (C is
MLA {<cond>}{S} <Rd >, <Rm>, <Rs>, <Rn> Accumulate
unpredictable)
MOV {<cond>}{S} <Rd>, <shifter_operand> Move N, Z, C
Move PSR into
MRS {<cond>} <Rd >, CPSR
eneral-Purpose None
MRS {<cond>} <Rd >, SPSR
Register
MSR {<cond>} CPSR_<fields>, #<immediate> Move to Status
MSR {<cond>} CPSR_<fields>, <Rm> Register from ARM N/A
MSR {<cond>} SPSR_<fields>, #<immediate> Register
MSR {<cond>} SPSR_<fields>, <Rm>
N, Z (C is
MUL {<cond>}{S} <Rd >, <Rm>, <Rs> Multiply
unpredictable)
MVN {<cond>}{S} <Rd>, <shifter_operand> Move Negative N, Z, C
ORR {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Bit-wise Inclusive-OR N, Z, C
RSB {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Reverse Subtract N, Z, V, C
Reverse Subtract
RSC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> N, Z, V, C
with Carry
SBC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Subtract with Carry N, Z, V, C
SMLAL{<cond>}{S} <Rd_LSW>, <Rd_MSW>, <Rm>, Signed Multiply- N, Z (V, C are
<Rs> Accumulate Long unpredict)
SMULL{<cond>}{S} <Rd_LSW>, <Rd_MSW>, <Rm>, N, Z (V, C are
<Rs> Signed Multiply Long unpredict)
46
Embedded System
#include <iolpc2148.h>
main
LDR R0,=0x0FF57341
LDR R1,=0xBF230EA1
ADD R3,R0,R1
NOP
END
#include <iolpc2148.h>
main
LDR R0,=0x4FFFFFEB
LDR R1,=0x07A21111
SUB R3,R0,R1
NOP
END
#include <iolpc2148.h>
47
Embedded System
main
LDR R0,=0x00012345
LDR R1,=0x00000012
MUL R3,R0,R1
NOP
END
#include <iolpc2148.h>
main
LDR R0,=0x0000AA19
LDR R1,=0x0000015E
LOOP1: SUBS R0,R0,R1
BLT LOOP
ADD R2,R2,#0X01
B LOOP1
LOOP: NOP
END
5. Write a program to the compare the contents of the memory locations 00000020h and
00000021h.
#include <iolpc2148.h>
main:
LDR R1,=0X00000020
LDR R0,[R1]
LDR R1,=0X00000021
LDR R3,[R1]
CMP R0,R3
BNE LOOP
MOV R0,#0XFFFFFFFF
B LOOP1
LOOP: MOV R0,#0X00000000
NOP
48
Embedded System
LOOP1: END
6. Shift the content of the memory location E0024004h for 5 times and move the result to
the memory location E002008h
#include <iolpc2148.h>
main:
LDR R1,=0XE0024004
LDR R0,[R1]
LSL R0, R0,#0X05
LDR R1,=0XE0028008
STR R0,[R1]
NOP
END
#include <iolpc2148.h>
main
LDR R0,=0XFFFFFFFF
LDR R1,=0X0000FFFF
AND R0,R0,R1
NOP
END
Exercises:
1. Write a program to add the contents of the memory locations 00000034h and 00000035h.
Store the result to the memory location 00000036h
49
Embedded System
2. Write a program to read the data from the location FF204712h and find whether the number
is odd or even
3. Write a program to divide 98ED40h by 9B5h. Move the quotient and remainder to the
memory locations 00000003h and 00000009h
4. Write a program Swap the content of the memory location FFFF0000h
5. Write a program to Move the data 99h to the memory locations from E0000000h to
E000FFFFh
6. Write a program to find the decimal equivalent of the hexadecimal data 45h
7. Write a program to Get ‘n’ data from the memory locations starting from 00000010h and find
the smallest
8. Write a program to sort an array of elements in the locations starting from E0024000h in
ascending order
9. Write a program to find the complement of the data in the memory location 00000056h
10. Write a program to check whether the ASCII value of the content in the memory location
F1928374h is small letter, capital letter, special character or number.
50
Embedded System
The largest measure of C's success seems to be based on purely practical considerations:
The portability of the compiler
The standard library concept
A powerful and varied repertoire of operators
An elegant syntax
Compilers produce hex files that we download into the ROM of the microcontroller. While
Assembly language produces a hex file that is much smaller than C, programming in Assembly
language is tedious and time consuming. C programming, on the other hand, is less time
consuming and much easier to write, but the hex file size produced is much larger than if we
used Assemble language.
pre-processor directives
global declarations
main()
{
local variables to function main ;
statements associated with function main ;
}
function1()
{
local variables to function 1 ;
statements associated with function 1 ;
}
function2()
{
local variables to function 2 ;
statements associated with function 2 ;
}
51
Embedded System
The compiler uses the following sizes for the various C data types:
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder after integer division (modulus)
Bit-Manipulating Operators
& AND
| OR
~ NOT
^ XOR
<< Shift Left
>> Shift Right
Relational Operators
< Less Than
<= Less Than Or Equal To
> Greater Than
>= Greater Than Or Equal To
Logical Operators
&& AND
|| OR
! NOT
Equality Operators
== Equal To
!= Not Equal To
Unary Operators
52
Embedded System
- Minus
++ Increment
-- Decrement
sizeof Size, in bytes
(type) Cast
Libraries
string.h - The standard ‘string.h’ library is provided using Floating Point options FP(BCD,ALL),
and contains the functions
strrchr, strcat, strncat, strops, strncpy, strcpy, strncmp, strlen, strchr
stdio.h - The standard ‘stdio.h’ library is provided using Floating Point options FP(BCD,ALL),
and contains the functions
getchar, ungetchar, gets, putchar, puts, printf, sprintf, scanf, sscanf
stdlib.h - The standard ‘stdlib.h’ library is provided using Floating-Point options FP (BCD, ALL),
and contains the functions
atof, atoi, atol, strtod, strtol, stroul, rand, srand, abs, labs
ctype.h - The standard ‘ctype.h’ library is provided using Floating-Point options FP (BCD, ALL),
and contains the functions
isalnum, isalpha, isascii, isdigit, isupper, islower, isxdigit, isspace, iscntrl, isprint, ispunct, toascii,
toupper
math.h - The standard ‘math.h’ library is provided using Floating-Point options FP (BCD, ALL),
and contains the functions
abs, acos, asin, atan, atan2, ceil, fabs, floor, fmod, exp, log, log10, modf, frexp, ldexp, sin, cos,
tan, sinh, cosh, tanh, sqrt, pow, acosf, asinf, atanf, atan2f, ceilf, fabsf, floorf, fmodf, expf, logf,
log10f, modff, frexpf, ldexpf, sinf, cosf, tanf, sinhf, coshf, tanhf, sqrtf, powf, acosl, asinl, atanl,
atan2l, ceill, fabsl, floorl, fmodll, expl, logl, log10l, modfl, frexpl, ldexpl, sinl, cosl, tanl, sinhl,
coshl, tanhl, sqrtl, powl
Keywords
Reserved keywords specified by the standard ‘C’ are given in the following table.
53
Embedded System
There are new reserved keywords for Embedded ‘C’. Some of them are pragma,
intrinsic, interrupt, and etc., _int64, _packed are some of the extended keywords used in
ARM compiler. These type qualifiers can be used to instruct the compiler to treat the qualified
type in a special way.
#include<iolpc2148.h>
int a,b,c;
void main()
{
a=0x62;
b=0x6C;
c=a+b;
printf("\n\rvalue of c is:%x",c);
}
#include<iolpc2148.h>
#include<stdio.h>
void main()
{
while(1)
{
printf("\n\rfactorial of given number is:%d",factorial(fact));
fact++;
}
}
54
Embedded System
int factorial(long x)
{
long c,f;
f=x;
c=f*(--x);
while(x!=1)
{
c=c*(--x);
}
return(c);
}
#include<iolpc2148.h>
#include<stdio.h>
int array[10]={23,12,45,67,89,9,97,107,46,78};
void main()
{
printf("\n\r maximum value is:%d",finding_max(array));
}
55
Embedded System
else
max=p[i];
}
return(max);
}
#include<iolpc2148.h>
#include<stdio.h>
void main()
{
while(1)
{
printf("\n\r Next prime number is :%d",finding_next_prime(current_prime));
current_prime=finding_next_prime(current_prime);
}
}
int finding_next_prime(int x)
{
int a=2,b;
x=x++;
while(a!=x)
{
b=x%a;
if(b==0)
{
x=x++;
a=2;
56
Embedded System
}
else
a=a++;
}
return(x);
}
#include<iolpc2148.h>
#include<stdio.h>
int array[10]={9,8,7,6,5,4,3,2,1,0};
int sorted[10];
void main()
{
sorting(array);
display(array);
}
for(i=0;i<10;i++)
for(j=i+1;j<10;j++)
{
if(p[j]<p[i])
{
buffer=p[i];
57
Embedded System
p[i]=p[j];
p[j]=buffer;
}
}
}
Exercises:
58
Embedded System
Key features
The IAR Embedded Workbench IDE is the framework where all necessary tools are
seamlessly integrated:
● The highly optimizing ARM IAR C/C++ Compiler
● The ARM IAR Assembler
● The versatile IAR XLINK Linker
● The IAR XAR Library Builder and the IAR XLIB Librarian
● A powerful editor
● A project manager
● A command line build utility
● IAR C-SPY® debugger, a state-of-the-art high-level language debugger.
59
Embedded System
Project management
The IAR Embedded Workbench IDE comes with functions that will help you to stay in
control of all project modules, for example, C or C++ source code files, assembler files, include
files, and other related modules. You create workspaces and let them contain one or several
projects. Files can be grouped, and options can be set on all levels—project, group, or file. This
guide demonstrates a typical development cycle and shows how you use the compiler and the
linker to create a small application for the ARM core. For instance, creating a workspace, setting
up a project with C source files, and compiling and linking your application.
1. To create a new project, choose Project>Create New Project. The Create New Project dialog
box appears, which lets you base your new project on a project template.
2. Make sure the Tool chain is set to ARM, and click OK.
3. For this tutorial, select the project template Empty project, which simply creates an empty
project that, uses default project settings.
4. In the standard Save As dialog box that appears, specify where you want to place your
project file, that is, in your newly created projects directory. Type project1 in the File name
box, and click Save to create the new project.
60
Embedded System
A project file—with the filename extension ewp—will be created in the projects directory,
not immediately, but later on when you save the workspace. This file contains information about
your project-specific settings, such as build options. Write the application code in the
corresponding space. The new file can be selected by File—New – File. Write the code and
save the file with the extension of (filename.c or filename.asm or filename.cpp) along with the
file name. If you choose the project template as either ASM, C or C++ while creating a new
project it is not necessary to save the file with the extension.
5. Before you add any files to your project, you should save the workspace. Choose File>Save
Workspace and specify where you want to place your workspace file.
A workspace file—with the filename extension eww—has now been created in the projects
directory. This file lists all projects that you will add to the workspace.
Creating several groups is a possibility for you to organize your source files logically
according to your project needs. Choose Project>Add Files to open a standard browse dialog
box. Locate the file(s), select them in the file selection list, and click Open to add them to the
61
Embedded System
project. Otherwise click the right mouse button on the project in the workspace window and
choose Add—Add “filename.c”.
Now you will set the project options. For application projects, options can be set on all
levels of nodes. First you will set the general options to suit the processor configuration in this
tutorial. Because these options must be the same for the whole build configuration, they must
be set on the project node.
1. Select the project folder icon project1 - Debug in the Workspace window and choose
Project>Options.
62
Embedded System
Click OK to set the options you have specified. The project is now ready to be built.
Now you should set up the options for the IAR XLINK Linker. Select Project>Options
then select Linker in the Category list to display the XLINK option pages. It is important to
choose the output format that suits your purpose. You might want to load it to a debugger—
which means that you need output with debug information.
In the Config window choose the appropriate flash.xcl file. Change the default directory
to the directory path mentioned here for LPC2148.
Now the application code is ready to be run in the IAR C-SPY Debugger where you can
watch variables, set breakpoints, view code in disassembly mode, monitor registers and
memory, and print the program output in the Terminal I/O window. Before starting the IAR C-
SPY Debugger you must set a few C-SPY options.
63
Embedded System
1. Choose Project>Options and then the Debugger category. On the Setup page, make sure
that you have chosen Simulator from the Driver drop-down list and that Run to main is selected.
Click OK.
2. Choose Project>Debug. Alternatively, click the Debugger button in the toolbar. The IAR C-
SPY Debugger starts with the project1.d79 application loaded. In addition to the windows
already opened in the Embedded Workbench, a set of C-SPY-specific windows are now
available.
At source level, the Step Over and Step Into commands allow you to execute your application a
statement or instruction at a time.
64
Embedded System
Steps to download the executable file (HEX file) from PC to Target Board
The flash boot loader code is executed every time the part is powered on or reset. The
loader can execute the ISP command handler or the user application code. A LOW level after
reset at the P0.14 pin is considered as an external hardware request to start the ISP command
handler.
If the settings mentioned above are made correct, the message window will show the message “
Read Part ID Successfully” when you click “Read Device ID” in the LPC2000 Flash Utility
window.
Then select the file to be loaded in the target device.
65
Embedded System
Click Upload to Flash, the previous contents in the memory is erased and the file is
loaded in the Flash memory.
66
Embedded System
Now the hardware is ready to execute the program. Keep the pin P0.14 in logical ‘1’ state
(connect the pin with 3.3V) opposite to the previous condition and press the RESET switch
once. You can get the result.
67
Embedded System
LPC2148
Power Supply
Microcontroller
Connector UART 0
CAN
Power On/Off Switch Connector
Regulator
UART 1
USB
Connector
RS-232
Driver
TFT LCD
12 MHz Crystal
Connector
Oscillator
LEDs
ADC
Input
Switch
Expansion
Header Program/
LCD Reset
32.748 kHz Execution
Crystal for Mode Switch Switch
RTC
Circuits
SW1
L1
1 P1 LED R1
1 2 VCC 330E
2 3 VCC VCC
3 GND
POWER ON/OFF SW CA SIO SOCKET (POWER ON LED)
68
Embedded System
TXD0 19 9
P0.0/TXD0/PWM1 P0.25/AD0.4/AOUT P0.25
RXD0 21 10
P0.1/RXD0/PWM3/EINT0 D+ D+
P0.2 22 11
P0.2/SCL0/CAP0.0 D- D-
P0.3 26 13
P0.3/SDA0/MAT0.0/EINT1 P0.28/AD0.1/CAP0.2/MAT0.2 ADC
SCK0 27 14
P0.4/SCK0/CAP0.1/AD0.6 P0.29/AD0.2/CAP0.3/MAT0.3 P0.29
MISO0 29 15
P0.5/MISO0/MAT0.1/AD0.7 P0.30/AD0.3/EINT3/CAP0.0 SSEL1
MOSI0 30 17
P0.6/MOSI0/CAP0.2/AD1.0 P0.31/UP_LED/CONNECT CONNECT
SSEL0 31
P0.7/SSEL0/PWM2/EINT2
TXD1 33 46
P0.8/TXD1/PWM4/AD1.1 P0.16/EINT0/MAT0.2/CAP0.2 INT
RXD1 34 47
P0.9/RXD1/PWM6/EINT3 P0.17/CAP1.2/SCK1/MAT1.2 TX0RTS
SW0 35 53
P0.10/RTS1/CAP1.0/AD1.2 P0.18/CAP1.3/MISO1/MAT1.3 TX1RTS
SW1 37 54
P0.11/CTS1/CAP1.1/SCL1 P0.19/MAT1.2/MOSI1/CAP1.2 RX0BF
LED0 38 55
P0.12/DSR1/MAT1.0/AD1.3 P0.20/MAT1.3/SSEL1/EINT3 P0.20
LED1 39 1
P0.13/DTR1/MAT1.1/AD1.4 P0.21/PWM5/AD1.6/CAP1.3 P0.21
P0.14 41 2
P0.14/DCD1/EINT1/SDA1 P0.22/AD1.7/CAP0.0/MAT0.0 P0.22
P0.15 45 58
P0.15/RI1/EINT2/AD1.5 P0.23/VBUS VBUS
U5
LPC 2148
LCD0 16 32 RS
12 P1.16/TRACEPKT0 P1.24/TRACECLK 28
LCD1 P1.17/TRACEPKT1 P1.25/EXTIN0 DIOW
LCD2 8 24 LCD_EN
4 P1.18/TRACEPKT2 P1.26/RTCK 64
LCD3 P1.19/TRACEPKT3 P1.27/TD0 P1.27
LCD4 48 60 P1.28
44 P1.20/TRACESYNC P1.28/TDI 56
LCD5 P1.21/PIPESTAT0 P1.29/TCK P1.29
LCD6 40 52 P1.30
36 P1.22/PIPESTAT1 P1.30/TMS 20
LCD7 P1.23/PIPESTAT2 P1.31/TRST- P1.31
6 23
18 VSS VDD 43
25 VSS VDD 51
42 VSS VDD 7
50 VSS VDDA +3.3V
59 VSS
C16 VSSA 62 XTALIN
22PF 3 XTAL1 61
RTXC1 XTAL2 MCLK
5
Y1 RTXC2
3 49
57 VBAT 63 +3.3V
C15 RESET- RESET- VREF
32.748KHz
22PF
R31
+3.3V P0.2 R17
+3.3V
1K +3.3V RS
1K
R29
C3 C2 +3.3V P0.3 R18
0.1uF 0.1uF 1K +3.3V DIOW
R26 1K
+3.3V SW1
69
Embedded System
U1
RESET- 1
RST VDD
5
VCC +3.3V
2
VSS
RESET 3 4 RSTSW-
RST MR
R32
R38 1K 1K
MCP1319MT - 45 +3.3V
R33 SW0
100E
SW3 C17
X1 18pF
MICRO SW
6 5
+3.3V VCC OUT XTA LIN
3 4
NC GND
12Mhz
+3.3V
+3.3V
SW5
R34
R41 1 1K
100K 2 1
P0.14 3 2
3
TINNY SW R35 SW1
100E
SW2 C18
18pF
MICRO SW
SW4
RSTSW- 1 2
MICRO SW
BR
LCD1 TP2
10K
1 VCC
2 VCC
3 BR
4 RS
5 DIOW
6 LCD_EN
7 LCD0
8 LCD1
9 LCD2
10 LCD3
11 LCD4
12 LCD5
13 LCD6
LCD7 R19
14 1K
15 VCC
16
17 RESET-
18
19 VCC
20
N_LCD DISPLAY
70
Embedded System
+3.3V
U4 C13 +3.3V
C7 1 16
0.1uF C1+ VCC 0.1uF P5
3 2 P0.25
C1- V+ 1 2
C8 4 6 C9
P0.2 3 4 P0.29
0.1uF C2+ V- 0.1uF P0.3 5 6 P0.20
5 15 P0.15 7 8 P0.21
11 C2- GND 14 P1.27 9 10 P0.22
TXD1 T1IN T1OUT TX1_OUT
RXD1 12 13 P1.28 11 12 VBUS
10 R1OUT R1IN 7 RX1_IN
TXD0 T2IN T2OUT TX0_OUT P1.29 13 14 CONNECT
RXD0 9 8 P1.30 15 16 SSEL0
R2OUT R2IN RX0_IN
P1.31 17 18 SSEL1
ICL232
VCC 19 20
20 PIN BOX CON.
P2
5
9
4
8
3
7 TX0_OUT
2
6 RX0_IN
1
+3.3V
P7
9 PIN 'D' MALE CON. 1 2 LCD0
TXD0 3 4 LCD1
RXD0 5 6 LCD2
TXD1 7 8 LCD3
RXD1 9 10 LCD4
SW0 11 12 LCD5
SW1 13 14 LCD6
P4 LED0 15 16 LCD7
1 TX1_OUT LED1 17 18 RS
2 RX1_IN VCC 19 20
3
20 PIN BOX CON.
3 PIN RMC
LED0 R21 L6
L3 330E LED
RX0_IN
LED R8
L2 1.5K +3.3V
TX0_OUT LED1 R20 L5
330E LED
LED
+3.3V
3
SP1
1 3 PIN SMD JMP P3
VCC 2 R30 100K2 TP1
1 2 ADC
3 10K
+3.3V 3 4
5 6
1
7 8
9 10
C_SSEL0 11 12 RX0BF
TX0RTS 13 14 INT
C_MISO0 15 16 C_MOSI0
C_SCK0 17 18
TX1RTS 19 20
20 PIN BOX CON.
71
Embedded System
+3.3V
R9
3K
P6
1
1 R28 10K VBUS Q1
VCC 2 R15 33E 2 R12
D- D- CONNECT
3 R11 33E D+ 1K
D+ 4 BC557
3
NC 5
GND R10
USB-B 15E
R27
22k C10 R14 L4
C11 1.5K LED
18pF 18pF
+3.3V
R13
15E
VCC U3
LM317
3 2
VIN VOUT
ADJ
+ C1
10MF/16V
1
+3.3V
+ C5 + C4 C6
R7 10MF/16V 10MF/16V 0.1uF
100E
R6
10E
P8
6
VDISPLAY 1 +3.3V
VDIGITAL
4 +3.3V
SCK T_SCK0
3 T_MOSI0
DIO 5 R16
CS T_SSEL0 LCD RST
7 33K
NC
2 LCD RST
RESET
10
VLRD BL_PWR
9
LEDGND
8
GND
TFT_ DISPLAY
72
Embedded System
+3.3V
C14
0.1uF
+3.3V
R4
R5
R3
R2
U2A
14
3.3K
3.3K
3.3K
3.3K
74VHC08
1 SSEL0
C_SSEL 0 3
2
U2B
74VHC08
4 MOSI0
C_MOSI0 6
5
+3.3V
U2C
74VHC08
9 SCK0
C_SCK0 8
10
+3.3V U2D
74VHC08
12
11 MISO0
C_MISO0 13
2
2 PIN SMD
2 PIN SMD
2 PIN SMD
2 PIN SMD
1
VCC
BD1 D1
R40 2.2E 220uH
BL_PWR
VCC
10 uF/6.3V
22 0uF/16 V
R36
5.6K + C19
PK
VCC
DC
U7
MC34063A 1
3 SWC
TCAP 2
SWE
R37
GND
C21 5
47pF FB
1.2K
4
73
Embedded System
+3.3V
3.3K
3.3K
3.3K
3.3K
C12
0.1uF
+3.3V
R24
R25
R22
R23
U6A
14
74VHC08
1 SSEL1
T_SSEL0 3
2
U6B
74VHC08
4 MOSI0
T_MOSI0 6
5
+3.3V
U6C
74VHC08
9 SCK0
T_SCK0 8
10
+3.3V U6D
74VHC08
12
11 MISO0
T_MISO0 13
7
74
Embedded System
I/O devices are used by a person (or other system) to communicate with a CPU. For
instance, keyboards and mouses are considered input devices of a computer, while monitors
and printers are considered output devices of a computer. The I/O devices are connected
through the ports. One major characteristic of the peripheral interface is whether it is serial or
parallel. In a parallel interface, there are multiple lines connecting the I/O module and the
peripheral, and multiple bits are transferred simultaneously, just as all of the bits of a word are
transferred simultaneously over the data bus. In a serial interface, there is only one line used to
transmit data, and bits must be transmitted one at a time. A parallel interface is commonly used
for higher-speed. The LPC2148 has two 32-bit General Purpose I/O ports. Port 0 is a 32-bit I/O
port with individual direction controls for each bit. Total of 28 pins of the Port 0 can be used as a
general purpose bi-directional digital I/Os while P0.31 provides digital output functions only. The
operation of port 0 pins depends upon the pin function selected via the pin connect block. Pins
P0.24, P0.26 and P0.27 are not available. Port 1 is a 32-bit bi-directional I/O port with individual
direction controls for each bit. The operation of port 1 pins depends upon the pin function
selected via the pin connect block. Pins 0 through 15 of port 1 are not available. PORT0 and
PORT1 are controlled via two groups of 4 registers IO0PIN, IO0SET, IO0DIR, IO0CLR for Port
0 and IO1PIN, IO1SET, IO1DIR, IO1CLR for Port 1.
The LPC2148 never actively outputs more than 3.3V. For logic 0 the voltage on the pin
is 0 volts and for logic 1 the volatage is 3.3V. We can connect digital outputs of a 5V device
directly to the LPC2148. Even if its supply voltage is only 3.3V it tolerates up to 5.5V on its
inputs. Simple output devices include lamps, light emitting diodes and 7-segment LED and LCD
displays, DC motor, Stepper Motor, etc,. The input devices covered are mechanical switches,
multiple position switches and keyboards, Sensors.
Before getting start with interfacing techniques we have to go through the pin connect
block. The pin connect block allows selected pins of the microcontroller to have more than one
function. Configuration registers control the multiplexers to allow connection between the pin
and the on chip peripherals. Peripherals should be connected to the appropriate pins prior to
being activated, and prior to any related interrupt(s) being enabled. Activity of any enabled
peripheral function that is not mapped to a related pin should be considered undefined.
Selection of a single function on a port pin completely excludes all other functions otherwise
available on the same pin. PINSEL0, PINSEL1 and PINSEL2 Registers are used to configure
the pin function. The PINSEL registers control the functions of device pins as shown below.
Pairs of bits in these registers correspond to specific device pins.
11 Reserved
75
Embedded System
76
Embedded System
77
Embedded System
78
Embedded System
Register Acc
Description Reset Value Address
Name ess
Note:
2. FIO0DIR, FIO1DIR, FIO0MASK, FIO1MASK, and etc., are some of the byte-accessible and
half-word accessible Registers.
79
Embedded System
Example
State of the output configured GPIO pin is determined by writes into the pin’s port
IOSET and IOCLR registers. Last of these accesses to the IOSET/IOCLR register will
determine the final output of a pin. In case of a code:
Therefore, when interfacing an LED to a TTL output, the maximum current through the
LED is 16 mA. The features of LEDs are listed below
Lower power consumption
Require series resistors to limit the current
Displaying decimal digits
P1.24
LED
330
80
Embedded System
LED lighting is an emerging technology with many home applications such as LED
Christmas lights, LED rope lights, LED spotlights, etc. LED bulbs last over 50,000 hours.
Program - Switch on and switch off the LEDs with the regular interval
81
Embedded System
32
P1.24/TRACECLK a
P1.25/EXTIN0 28 b
33 0 ohm
g f a b
P1.26/RT CK 24 c
P1.27/AD0 64 d
P1.28/AD1 60 e
vcc
P1.29/TCK 56 f
P1.30/TMS 52 g
e d c dp
P1.31/TRST
20 dp
Seven-segment displays are found in Pocket calculators, Sign boards, Counting circuits
and etc..
#include "iolpc2148.h"
void main()
{
IO1DIR=0xFF000000;
while(1)
{
for(i=0;i<10;i++)
{
IO1PIN=disp[i]<<24;
delay();
}
}
82
Embedded System
void delay()
{
long int i;
for(i=0;i<1000000;i++);
}
Liquid crystals are a phase of matter whose order is intermediate between that of a liquid
and that of a crystal. The molecules are typically rod-shaped organic matters about 25
Angstroms in length and their ordering is a function of temperature. The molecular orientation
can be controlled with applied electric fields. LCD is made up of two sheets of polarizing
material with the liquid crystal solution between them. An electric current passed through the
liquid causes the crystals to align so that light cannot pass through them, which results in
display of character as per the applied voltage in its data lines. The driver is provided to drive
the LCD. It stores the display data transferred from the microcontroller in the internal display
RAM and generates dot matrix liquid crystal driving signals. Each bit data of display RAM
corresponds to on/off state of a dot of a liquid crystal display.
LCDs available in two models: character LCD and Graphics LCD. The character LCD
displays ASCII values and graphics LCD displays graphics. Character LCDs are available in
various kinds of models.
1. No. Of characters Lines: 81, 161, 162, 164, 204, 404,…
2. Dots Dots: 12232, 12864, 240128, 320240,….
3. Color: Yellow, Green, Gray, Blue….
Graphics LCDs are also available with different sizes and colors.
83
Embedded System
BR1
VCC 10K
1
VCC 2
BR1 3
RS
P1.24/TRACECLK 32 4
RW
P1.25/EXTINO 28 5
EN
P1.26/AD0 24 6
D0
P1.16/TRACEPKT0 16 7
LCD
D1
P1.17/TRACEPKT1 12 8
D2
P1.18/TRACEPKT2 8 9
D3
P1.19/TRACEPKT3 4 10
D4
P1.20/TRACESYNC 48 11
D5
P1.21/PIPESTST0 44 12
D6
P1.22/PIPESTAT1 40 13
D7
P1.23/PIPESTST2 36 14
VCC 15
16
Fig. 12.3: LCD Types, Character LCD, LCD pin diagram, Interfacing Circuit
VCC, GND AND V0 - While VCC and VSS provide +5V and ground, respectively; V0 is used for
controlling LCD contrast.
RW (Read/Write) - RW allows the user to write information to the LCD or read information from
it. RW=1 when reading; RW=0 when writing.
EN (Enable) - The LCD to latch information presented to its data pins uses the enable pin.
When data is supplied to data pins, a high to low pulse must be applied to this pin in order for
the LCD to latch in the data present at the data pins.
D0 – D7 - The 8-bit data pins, are used to send information to the LCD or read the contents of
the LCD’s internal registers. To display letters and numbers, we send ASCII codes for the letters
A-Z, a-z, and numbers 0-9 to these pins while making RS = 1.
84
Embedded System
Program - Display “Vi Microsystems” in the first line and “Chennai-96” in the second line
#include<IOLPC2148.h>
void delay();
#define RS IO1PIN_bit.P1_24
#define RW IO1PIN_bit.P1_25
#define EN IO1PIN_bit.P1_26
#define Busyflag IO1PIN_bit.P1_23
void main()
{
IO1DIR = 0x07FF0000;
RS=0;
RW=0;
EN=0;
delay();
for(i=0;i<5;i++)
{
delay();
IO1DIR=0x07FF0000;
IO1PIN=(command[i]<<16);
RS=0;
RW=0;
EN=1;
EN=0;
}
for(i=0;i<16;i++)
{
delay();
IO1DIR=0x07FF0000;
IO1PIN=(dat[i]<<16);
RS=1;
RW=0;
EN=1;
EN=0;
}
delay();
IO1DIR=0x07FF0000;
IO1PIN=(0xC0<<16);
RS=0;
RW=0;
EN=1;
EN=0;
for(i=0;i<16;i++)
{
85
Embedded System
delay();
IO1DIR=0x07FF0000;
IO1PIN=(dat1[i]<<16);
RS=1;
RW=0;
EN=1;
EN=0;
}
while(1);
}
void delay()
{
RW=1;
RS=0;
EN=0;
IO1DIR=0x07000000;
busy:
EN=0;
EN=1;
if(Busyflag==1)
goto busy;
EN=0;
}
The stepper motor can be operated in three different stepping modes, namely, full-step,
half-step, and micro-step. The main feature of this switching sequence is that you can double
the resolution of the stepper motor by causing the rotor to move half the distance it does when
the full-step switching sequence is used. This means that a 200-step motor, which has a
resolution of 1.8°, will have a resolution of 400 steps and 0.9°. The stepper motor uses a four-
step switching sequence, which is called a full-step switching sequence. The stepper motor
uses a eight-step switching sequence, which is called a half-step switching sequence. The full-
step and half-step motors tend to be slightly jerky in their operation as the motor moves from
86
Embedded System
step to step. The amount of resolution is also limited by the number of physical poles that the
rotor can have. The amount of resolution (number of steps) can be in-creased by manipulating
the current that the controller sends to the motor during each step. In fact it is possible for the
controller to reach as many as 500 micro steps for a full-step sequence, which will provide
100,000 steps for each revolution.
Stepper
Motor
In order to keep the motor’s power loss within a reasonable limit, the current in the windings
must be controlled. The stepper motor driver circuit has two major tasks:
To change the current and flux direction in the phase windings
To drive a controllable amount of current through the windings, and enabling as
short current rise and fall times as possible for good high speed performance.
Darlington transistors are normally used for driving circuit. Each winding need a
darlington transistor, which is a transistor pair. L298 is the single IC that performs the same
function of darlington transistors. The interfacing circuit is shown below.
87
Embedded System
Program – Rotate the stepper motor for 360 degrees in forward diretion and 360 degrees
in reverse direction
#include<IOLPC2148.h>
void main()
{
stepperfwd(50);
stepperdelay();
stepperrev(50);
while(1);
}
88
Embedded System
void stepperdelay()
{
unsigned long k;
for(k=0;k<5000;k++);
}
89
Embedded System
Input port is essential to interface with the external world. The input devices are
switches, keys, ADC, and sensors. IO0DIR and IO1DIR have default value of 0x00000000 so
by default port pins are configured as input. Also, a pin once configured as output can not be
used as input unless the value of corresponding IODIR register is changed.
Let us see the working of the input port. When a HIGH is applied to a TTL input it draws
very little current. When a LOW is applied to a TTL input it sources approximately 4 mA. When
the digital input is HIGH the transistor will be turned on. This results in a direct path from the
port pin to ground, therefore the pin is logic 0. When the digital input is LOW the transistor is off
which means there is no path for current from the collector to the emitter, therefore the port pin
will read 5V. This circuit results in logic inversion, but this should not be a problem as inverting
the port pin through software is very easy.
An electrical switch is any device used to interrupt the flow of electrons in a circuit.
Switches are essentially binary devices: they are either completely on ("closed") or completely
off ("open").. In the simplest case, a switch has two pieces of metal called contacts that touch to
make a circuit, and separate to break the circuit. Push button switch is one of the mostly used
type.
P1.16/TRACEPKT 0 16 1 2
P1.17/TRACEPKT 1 12 1 2
P1.18/TRACEPKT 2 8 1 2
P1.19/TRACEPKT 3 4 1 2
P1.20/TRACESYNC 48 1 2
P1.21/PIPESTST 0 44 1 2
P1.22/PIPESTAT 1 40 1 2
P1.23/PIPESTST 2 36 1 2
90
Embedded System
When the switch is open, no current flows through the resistor and therefore the voltage
on the microcontroller pin is 3.3 V. When the switch is closed the pin is connected directly to
ground. As before, when the TTL input is HIGH practically no current flows in the circuit and
when the input is LOW there is a direct current for the 3 A that may flow from the pin.
A push button switch is used to either close or open an electrical circuit depending on
the application. Push button switches are used in various applications such as industrial
equipment control handles, outdoor controls, mobile communication terminals, and medical
equipment, and etc.
#include "iolpc2148.h"
void delay();
void main()
{
loop:
IO0DIR=0x00000000;
if(SW1==0)
{
IO0DIR=0x00003000;
IO0PIN=0x00001000;
delay();
}
else if(SW2==0)
{
IO0DIR=0x00003000;
IO0PIN=0x00002000;
delay();
}
else
{
IO0DIR=0x00003000;
IO0PIN=0x00000000;
}
goto loop;
91
Embedded System
void delay()
{
long int i;
for(i=0;i<10000;i++);
}
A sensor is a device, which measures a physical quantity and converts it into a signal,
which can be read by an observer or by an instrument. Sensors are classified according to the
physical properties. Temperature sensor, pressure sensor, humidity sensor, wind velocity
sensor, acceleration sensor, flow sensor, level sensor, strain gauge, touching sensor, proximity
sensors are the most common types of sensors. Touching sensor and proximity sensors are
interfaced with microcontroller through the digital input lines. The remaining sensors are
connected through Analog to Digital Converter. Here the IR (Infra Red) sensor is explained in
detail. An Infra Red sensor is an electronic device, which measures infrared light radiating from
objects in its field of view.
HI
VCC 5V
K
2N2222A A
LED
0 0
10K
1K o/p
To
2N2222A
Microcontroller
Pin
0
Fig.13.2: IR sensor, Symbol and interfacing circuit
92
Embedded System
IR sensors are used in edge detection in robotics, Digital cameras and for object
counting circuits.
Program in ‘C’ – Display the number of objects passed through using 7-segment LED
#include<IOLPC2148.h>
void delay();
void main()
{
while(1)
{
IO0DIR=0X00000000;
if(sensor==1)
{
count=count+1;
if(count>9)
count=0;
IO0DIR=0xFF000000;
IO0PIN=disp[count]<<24;
while(sensor==1);
delay();
}
}
void delay()
{
int m;
for(m=0;m<200;m++);
}
93
Embedded System
There are two basic types of serial communications, synchronous and asynchronous.
With synchronous communications, the two devices initially synchronize themselves to each
other, and then continually send characters to stay in sync. Even when data is not really being
sent, a constant flow of bits allows each device to know where the other is at any given time.
That is, each character that is sent is either actual data or an idle character. Synchronous
communications allows faster data transfer rates than asynchronous methods, because
additional bits to mark the beginning and end of each data byte are not required.
Asynchronous means "no synchronization", and thus does not require sending and
receiving idle characters. However, the beginning and end of each byte of data must be
identified by start and stop bits. The start bit indicates when the data byte is about to begin and
the stop bit signals when it ends. The requirement to send these additional two bits causes
asynchronous communication to be slightly slower than synchronous however it has the
advantage that the processor does not have to deal with the additional idle characters. An
asynchronous line that is idle is identified with a value of 1 (also called a mark state). By using
this value to indicate that no data is currently being sent, the devices are able to distinguish
between an idle state and a disconnected line. When a character is about to be transmitted, a
start bit is sent. A start bit has a value of 0 (also called a space state). Thus, when the line
switches from a value of 1 to a value of 0, the receiver is alerted that a data character is about
to be sent.
94
Embedded System
SPI (Serial Peripheral Interface) and I2C (Inter-Integrated Circuit) are the examples for
synchronous mode of data transfer. UART (Universal Asynchronous Receiver Transmitter),
USB (Universal Serial Bus), Ethernet, CAN (Controller Area Network) are the examples for
asynchronous type of communication.
One of the LPC2148s many powerful features is its integrated UART, otherwise known
as a serial port. The fact that the LPC2148 has an integrated serial port means that you may
very easily read and write values to the serial port. If it were not for the integrated serial port,
writing a byte to a serial line would be a rather tedious process requiring turning on and off one
of the I/O lines in rapid succession to properly "clock out" each individual bit, including start bits,
stop bits, and parity bits. However, we do not have to do this. Instead, we simply need to
configure the serial ports operation mode and baud rate. Once configured, all we have to do is
write to an SFR to write a value to the serial port or read the same SFR to read a value from the
serial port. The LPC2148 will automatically let us know when it has finished sending the
character we wrote and will also let us know whenever it has received a byte so that we can
process it. We do not have to worry about transmission at the bit level--which saves us quite a
bit of coding and processing time. UART or Serial ports, also called communication (COM)
ports, RS-232 ports are bi-directional. The LPC2148 contain two UARTs. In addition to standard
transmit and receive data lines, the UART1 also provides a full modem control handshake
interface.
All of the SFRs associated with UART0 most important SFRs are explained in detail.
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 prescaler 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
95
Embedded System
contains the higher 8 bits of the divisor. The Divisor Latch Access Bit (DLAB) in U0LCR must be
one in order to access the UART0 Divisor Latches. The UART0 Fractional Divider Register
(U0FDR) controls the clock prescaler for the baud rate generation and can be read and written
at user’s discretion. This prescaler takes the VPB clock and generates an output clock per
specified fractional requirements.
Where PCLK is the peripheral clock, U0DLM and U0DLL are the standard UART0 baud
rate divider registers, and DIVADDVAL and MULVAL are UART0 fractional baudrate generator
specific parameters.
The value of MULVAL and DIVADDVAL should comply to the following conditions:
1. 0 < MULVAL ≤ 15
2. 0 ≤ DIVADDVAL ≤ 15
RBR Interrupt Enable - Enables the Receive Data Available interrupt for UART0. It also
controls the Character Receive Time-out interrupt.
0 Disable the RDA interrupts.
1 Enable the RDA interrupts.
THRE Interrupt Enable - Enables the THRE interrupt for UART0. The status of this can be read
from U0LSR.
0 Disable the THRE interrupts.
1 Enable the THRE interrupts.
RX Line Status Interrupt Enable - Enables the UART0 RX line status interrupts. The status of
this interrupt can be read from U0LSR.
0 Disable the RX line status interrupts.
1 Enable the RX line status interrupts.
96
Embedded System
The U0LCR determines the format of the data character that is to be transmitted or received.
The U0LSR is a read-only register that provides status information on the UART0 TX
and RX blocks.
97
Embedded System
Receiver Data Ready (RDR) - U0LSR0 is set when the U0RBR holds an unread character and
is cleared when the UART0 RBR FIFO is empty.
0 U0RBR is empty.
1 U0RBR contains valid data.
Overrun Error (OE) - The overrun error condition is set as soon as it occurs. An U0LSR read
clears U0LSR1. U0LSR1 is set when UART0 RSR has a new character assembled and the
UART0 RBR FIFO is full. In this case, the UART0 RBR FIFO will not be overwritten and the
character in the UART0 RSR will be lost.
0 Overrun error status is inactive.
1 Overrun error status is active.
Parity Error (PE) - When the parity bit of a received character is in the wrong state, a parity
error occurs. An U0LSR read clears U0LSR[2]. Time of parity error detection is dependent on
U0FCR[0]. A parity error is associated with the character at the top of the UART0 RBR FIFO.
0 Parity error status is inactive.
1 Parity error status is active.
Framing Error (FE) - When the stop bit of a received character is a logic 0, a framing error
occurs. An U0LSR read clears U0LSR[3]. The time of the framing error detection is dependent
on U0FCR0. Upon detection of a framing error, the Rx will attempt to resynchronize to the data
and assume that the bad stop bit is actually an early start bit. However, it cannot be assumed
that the next received byte will be correct even if there is no Framing Error.
Note: A framing error is associated with the character at the top of the UART0 RBR FIFO.
0 Framing error status is inactive.
1 Framing error status is active.
Break Interrupt (BI) - When RXD0 is held in the spacing state (all 0’s) for one full character
transmission (start, data, parity, stop), a break interrupt occurs. Once the break condition has
been detected, the receiver goes idle until RXD0 goes to marking state (all 1’s). An U0LSR read
clears this status bit. The time of break detection is dependent on U0FCR[0].
Note: The break interrupt is associated with the character at the top of the UART0 RBR FIFO.
0 Break interrupt status is inactive.
1 Break interrupt status is active.
Transmitter Holding Register Empty (THRE) - THRE is set immediately upon detection of an
empty UART0 THR and is cleared on a U0THR write.
0 U0THR contains valid data.
1 U0THR is empty.
Transmitter Empty (TEMT) - TEMT is set when both U0THR and U0TSR are empty; TEMT is
cleared when either the U0TSR or the U0THR contain valid data.
0 U0THR and/or the U0TSR contains valid data.
1 U0THR and the U0TSR are empty.
Error in RX FIFO (RXFE) - U0LSR[7] is set when a character with a Rx error such as framing
error, parity error or break interrupt, is loaded into the U0RBR. This bit is cleared when the
U0LSR register is read and there are no subsequent errors in the UART0 FIFO.
0 U0RBR contains no UART0 RX errors or U0FCR[0]=0.
1 UART0 RBR contains at least one UART0 RX error.
UART0 Scratch Pad Register (U0SCR), UART0 Auto Baud Generator Register(U0ACR-
controls the process of measuring the incoming clock/data rate for the baud rate generation)
and UART0 Transmit Enable Register (U0TER) are some of the additional registers used for
UART0 operation. UART1 is identical to UART0, with the addition of a modem interface. The
signals additional to RXD1 and TXD1 are CTS1, DCD1, DSR1, DTR1, RI1 and RTS1. The
register organization of UART 1 is
98
Embedded System
The register description is also identical to UART0 except U1MCR and U1MSR.
DTR Control - Source for modem output pin, DTR. This bit reads as 0 when modem loopback
mode is active.
RTS Control - Source for modem output pin RTS. This bit reads as 0 when modem loopback
mode is active.
Loopback Mode Select - The modem loopback mode provides a mechanism to perform
diagnostic loopback testing. Serial data from the transmitter is connected internally to serial
input of the receiver. Input pin, RXD1, has no effect on loopback and output pin, TXD1 is held in
marking state. The four modem inputs (CTS, DSR, RI and DCD) are disconnected externally.
Externally, the modem outputs (RTS, DTR) are set inactive. Internally, the four modem outputs
are connected to the four modem inputs. As a result of these connections, the upper four bits of
the U1MSR will be driven by the lower four bits of the U1MCR rather than the four modem
inputs in normal mode. This permits modem status interrupts to be generated in loopback mode
by writing the lower four bits of U1MCR.
0 Disable modem loopback mode
1 Enable modem loopback mode.
RTSen - Auto-RTS control bit.
0 Disable auto-RTS flow control.
1 Enable auto-RTS flow control.
CTSen – Auto-CTS control bit.
0 Disable auto-CTS flow control.
99
Embedded System
Delta CTS - Set upon state change of input CTS. Cleared on an U1MSR read.
0 No change detected on modem input, CTS.
1 State change detected on modem input, CTS.
Delta DSR - Set upon state change of input DSR. Cleared on an U1MSR read.
0 No change detected on modem input, DSR.
1 State change detected on modem input, DSR.
Trailing Edge RI - Set upon low to high transition of input RI. Cleared on an U1MSR read.
0 No change detected on modem input, RI.
1 Low-to-high transition detected on RI.
Delta DCD - Set upon state change of input DCD. Cleared on an U1MSR read.
0 No change detected on modem input, DCD.
1 State change detected on modem input, DCD.
CTS - Clear To Send State. Complement of input signal CTS. This bit is connected to
U1MCR[1] in modem loopback mode.
DSR - Data Set Ready State. Complement of input signal DSR. This bit is connected to
U1MCR[0] in modem loopback mode.
RI - Ring Indicator State. Complement of input RI. This bit is connected to U1MCR[2] in modem
loopback mode.
DCD - Data Carrier Detect State. Complement of input DCD. This bit is connected to U1MCR[3]
in modem loopback mode.
The RS232 standard was set long before the advent of the TTL logic family; its input and
output voltage levels are not TTL compatible. In RS232, a logic ’1’ is represented by -3 to -25 V,
while a logic’0’ bit is +3 to +25 V, making -3 to +3 undefined, For this reason, to connect any
RS232 to a microcontroller system we must use converters such as MAX232 to convert TTL
Logic levels to the RS232 voltage level, and vice versa. MAX232 IC Chips are commonly
referred to as line drivers.
100
Embedded System
#include <iolpc2148.h>
NOP
LDR R0,=VPBDIV
MOV R1,#0X01
STR R1,[R0]
LDR R0,=U0LCR
MOV R1,#0X83
STR R1,[R0]
LDR R0,=U0DLL
MOV R1,#0X4E
STR R1,[R0]
LDR R0,=U0DLM
MOV R1,#0X00
STR R1,[R0]
LDR R0,=U0LCR
MOV R1,#0X03
STR R1,[R0]
LDR R0,=PINSEL0
MOV R1,#0X00000005
STR R1,[R0]
LDR R0,=U0THR
MOV R1,#0X61 //Character ‘a’
STR R1,[R0]
CHECK:
LDR R0,=U0LSR
LDR R1,[R0]
MOV R2,#0X20
AND R1,R1,#0X20
CMP R1,R2
BNE CHECK
Programs - Read a byte from serial port at 9600bps. Check the data is either a, b or c and
transfer A,B and C accordingly.
#include "iolpc2148.h"
void delay();
unsigned char a;
void main()
{
VPBDIV = 0x01;
U0LCR = 0x83; //Uart0 Line Control Register, 8-bit data, DLAB=1
U0DLL=0x4E; //U0DLL: UART0 Divisor Latch (LSB),9600 bps
101
Embedded System
102
Embedded System
PINSEL0=0x00000001;
U0THR=0x20;
while((U0LSR&0x20)!=0x20);
delay();
}
goto start;
}
void delay()
{
int i;
for(i=0;i<1000;i++);
}
Note:
The routines: getchar(), putchar(), scanf(), printf(), etc. default to the LPC2148 serial port.
Instead of moving the data to U0THR we can simply write putchar(0x30). In the same way
Instead of checking the status of U0LSR and reading the data from U0RBR we can simply write
value=getchar().The scanf function reads data from the input stream using the getchar routine.
Data input are stored in the locations specified by argument. The printf function formats a series
of strings and numeric values and builds a string to write to the output stream using the
putchar function.
Eg: - Program to read 10 numbers from serial port and add the values.
#include "iolpc2148.h"
void delay();
unsigned char input[10];
unsigned long int i,result;
void main()
{
VPBDIV=1; //PCLK=CCLK
U0LCR = 0x83; //DLAB=1,8-data bits
U0DLL = 0x4E;
U0DLM = 0x00; //Set Baudrate as 9600bps
U0LCR = 0x01;
PINSEL0 = 0x00000005; //Enable Transmit line
for(i=0;i<10;i++)
{
input[i]=getchar();
}
result=0;
103
Embedded System
for(i=0;i<10;i++)
{
result=result+input[i];
}
printf(“The result is %lx”,result);
}
Serial port is the simple, Reliable and low-cost data transmission method, which enables
point-to-pint link. Most of the embedded CPUs have inbuilt serial port feature to establish a
connection with other devices. UART1 is identical in operation except the Special Function
Registers.
104
Embedded System
15 TIMER
The LPC2148 microcontroller comes equipped with two timers, each of which may be
controlled, set, read, and configured individually. The Timer/Counter is designed to count cycles
of the peripheral clock (PCLK) or an externally-supplied clock, and can optionally generate
interrupts or perform other actions at specified timer values, based on four match registers. It
also includes four capture inputs to trap the timer value when an input signal transitions,
optionally generating an interrupt. The applications of Timer are
105
Embedded System
All of the registers associated with Timer, only most important registers are explained in detail.
The Interrupt Register consists of four bits for the match interrupts and four bits for the
capture interrupts. If an interrupt is generated then the corresponding bit in the IR will be high.
Otherwise, the bit will be low. Writing a logic one to the corresponding IR bit will reset the
interrupt. Writing a zero has no effect.
106
Embedded System
The Timer Control Register is used to control the operation of the Timer/Counter.
Counter Enable - When one, the Timer Counter and Prescale Counter are enabled for
counting. When zero, the counters are disabled.
Counter Reset - When one, the Timer Counter and the Prescale Counter are synchronously
reset on the next positive edge of PCLK. The counters remain reset until TCR[1] is returned to
zero.
The Count Control Register is used to select between Timer and Counter mode, and in
Counter mode to select the pin and edge(s) for counting.
Counter/Timer Mode - This field selects which rising PCLK edges can increment Timer’s
Prescale Counter (PC), or clear PC and increment Timer Counter (TC).
00 Timer Mode: every rising PCLK edge
01 Counter Mode: TC is incremented on rising edges on the CAP input selected by
bits 3:2.
10 Counter Mode: TC is incremented on falling edges on the CAP input selected by
bits 3:2.
11 Counter Mode: TC is incremented on both edges on the CAP input selected by
bits 3:2.
Count Input Select - When bits 1:0 in this register are not 00, these bits select which CAP pin
is sampled for clocking:
00 CAPn.0 (CAP0.0 for TIMER0 and CAP1.0 for TIMER1)
01 CAPn.1 (CAP0.1 for TIMER0 and CAP1.1 for TIMER1)
10 CAPn.2 (CAP0.2 for TIMER0 and CAP1.2 for TIMER1)
11 CAPn.3 (CAP0.3 for TIMER0 and CAP1.3 for TIMER1)
The Capture Control Register is used to control whether one of the four Capture
Registers is loaded with the value in the Timer Counter when the capture event occurs, and
whether an interrupt is generated by the capture event. Setting both the rising and falling bits at
the same time is a valid configuration, resulting in a capture event for both edges.
107
Embedded System
CAP0RE
1 Capture on CAPn.0 rising edge: a sequence of 0 then 1 on CAPn.0 will cause
CR0 to be loaded with the contents of TC.
0 This feature is disabled.
CAP0FE
1 Capture on CAPn.0 falling edge: a sequence of 1 then 0 on CAPn.0 will cause
CR0 to be loaded with the contents of TC.
0 This feature is disabled.
CAP0I
1 Interrupt on CAPn.0 event: a CR0 load due to a CAPn.0 event will generate an
interrupt.
0 This feature is disabled.
CAP1RE
1 Capture on CAPn.1 rising edge: a sequence of 0 then 1 on CAPn.1 will cause
CR1 to be loaded with the contents of TC.
0 This feature is disabled.
CAP1FE
1 Capture on CAPn.1 falling edge: a sequence of 1 then 0 on CAPn.1 will cause
CR1 to be loaded with the contents of TC.
0 This feature is disabled.
CAP1I
1 Interrupt on CAPn.1 event: a CR1 load due to a CAPn.1 event will generate an
interrupt.
0 This feature is disabled.
CAP2RE
1 Capture on CAPn.2 rising edge: A sequence of 0 then 1 on CAPn.2 will cause
CR2 to be loaded with the contents of TC.
0 This feature is disabled.
CAP2FE
1 Capture on CAPn.2 falling edge: a sequence of 1 then 0 on CAPn.2 will cause
CR2 to be loaded with the contents of TC.
0 This feature is disabled.
CAP2I
1 Interrupt on CAPn.2 event: a CR2 load due to a CAPn.2 event will generate an
interrupt.
0 This feature is disabled.
CAP3RE
1 Capture on CAPn.3 rising edge: a sequence of 0 then 1 on CAPn.3 will cause
CR3 to be loaded with the contents of TC.
0 This feature is disabled.
CAP3FE
1 Capture on CAPn.3 falling edge: a sequence of 1 then 0 on CAPn.3 will cause
CR3 be loaded with the contents of TC
0 This feature is disabled.
CAP3I
1 Interrupt on CAPn.3 event: a CR3 load due to a CAPn.3 event will generate an
interrupt.
0 This feature is disabled.
108
Embedded System
X= Desired delay
Time taken to execute an instruction (Tins)
Tins=No. Of Machine Cycle No. Of Clock cycles for 1 Machine Cycle/Crystal Frequency
The maximum delay generated by the LPC2148 timer is (FFFFFFFF 250 ns) 1073
seconds without prescaler settings. By using prescaler we can get more and more delays.
For example, the value to be loaded in the timer to generate the delay of 1 second is derived
below.
X = 1s/250ns = 4000000 3(for an instruction) = 12000000(d) = B71B00(h). It means, the timer
is incremented from 00000000h to 00B71B00h for 1 second. Otherwise,
Y=Maximum value to be loaded – X
Y = FFFFFFFF(h) – B71B00(h) = FF48E4FFh
If the timer is loaded as FF48E4FFh it will take 1 second to overflow (FFFFFFFFh).
Program – Send a string “timer” to the serial port for every 5 seconds.
#include<IOLPC2148.h>
#include<stdio.h>
void main()
{
while(1)
{
VPBDIV=0X01; //VLSI Peripheral Bus in same frequency
U0LCR=0X83; // Enables the divisor latch bit and 8 bit data
U0DLL=0X4E; //UART Divisor Latch LSB
U0DLM=0X00; //UART Divisor Latch MSB
U0LCR=0X03; // Enables the divisor latch bit.
PINSEL0=0X00000005;//Pin function Select'0', to set the transmit bit
loop:
T0TC=0;
T0PR=0;
T0TCR=1;
rept:
if(T0TC<=0X03938700)
goto rept;
printf("timer") ;
goto loop;
}
}
109
Embedded System
16 INTERRUPTS
As stated earlier, program flow is always sequential, being altered only by those
instructions, which expressly cause program flow to deviate in some way. However, interrupts
give us a mechanism to "put on hold" the normal program flow, execute a subroutine, and then
resume normal program flow as if we had never left it. This subroutine, called an interrupt
handler (Interrupt service Routine), is only executed when a certain event (interrupt) occurs. The
event may be one of the timers "overflowing," receiving a character via the serial port,
transmitting a character via the serial port, or one of two "external events." The LPC2148 has
Vectored Interrupt Controller. The Vectored Interrupt Controller (VIC) takes 32 interrupt request
inputs and programmably assigns them into 3 categories, FIQ, vectored IRQ, and non-vectored
IRQ. The programmable assignment scheme means that priorities of interrupts from the various
peripherals can be dynamically assigned and adjusted.
Fast Interrupt reQuest (FIQ) requests have the highest priority. If more than one request
is assigned to FIQ, the VIC ORs the requests to produce the FIQ signal to the ARM processor.
The fastest possible FIQ latency is achieved when only one request is classified as FIQ,
because then the FIQ service routine can simply start dealing with that device. But if more than
one request is assigned to the FIQ class, the FIQ service routine can read a word from the VIC
that identifies which FIQ source(s) is (are) requesting an interrupt. Vectored IRQs have the
middle priority, but only 16 of the 32 requests can be assigned to this category. Any of the 32
110
Embedded System
requests can be assigned to any of the 16 vectored IRQ slots, among which slot 0 has the
highest priority and slot 15 has the lowest. Non-vectored IRQs have the lowest priority.
The VIC ORs the requests from all the vectored and non-vectored IRQs to produce the
IRQ signal to the ARM processor. The IRQ service routine can start by reading a register from
the VIC and jumping there. If any of the vectored IRQs are requesting, the VIC provides the
address of the highest-priority requesting IRQs service routine, otherwise it provides the
address of a default routine that is shared by all the non-vectored IRQs. The default routine can
read another VIC register to see what IRQs are active. All registers in the VIC are word
registers. Byte and halfword reads and write are not supported.
111
Embedded System
The ability to interrupt normal program execution when certain events occur makes it
much easier and much more efficient to handle certain conditions. If it were not for interrupts we
would have to manually check in our main program whether the timers had over flown, whether
we had received another character via the serial port, or if some external event had occurred.
Besides making the main program ugly and hard to read, such a situation would make our
program inefficient since wed be burning precious "instruction cycles" checking for events that
usually don’t happen.
Interrupt Sources
Block Flag(s)
112
Embedded System
113
Embedded System
114
Embedded System
#include "iolpc2148.h"
#include "intrinsics.h"
void main()
{
VPBDIV = 0x01;
U0LCR = 0x83;
U0DLL=0x4E;
U0DLM=0x00;
U0LCR=0x03;
intenable();
while(1)
{
printf("Normal Routine ");
}
}
115
Embedded System
void intenable()
{
PINSEL1_bit.P0_16=0x01;
PINSEL0_bit.P0_3=0x3;
PINSEL0_bit.P0_15=0x02;
int0en=0;
int1en=0;
int2en=0;
#pragma vector=0x18
__irq __arm void IRQ_ISR_Handler (void)
{
void (*interrupt_function)();
unsigned int vector;
vector = VICVectAddr;
interrupt_function = (void(*)())vector;
(*interrupt_function)();
VICVectAddr = 0;
}
void int0(void)
{
EXTINT_bit.EINT0 = 1;
116
Embedded System
if(!EXTINT_bit.EINT0)
{
printf("Interrupt 0 ");
}
}
void int1(void)
{
EXTINT_bit.EINT1 = 1; // Try to reset external interrupt flag.
if(!EXTINT_bit.EINT1) // Check if flag was reset (button not pressed).
{
printf("Interrupt 1 ");
}
}
void int2(void)
{
EXTINT_bit.EINT2 = 1; // Try to reset external interrupt flag.
if(!EXTINT_bit.EINT2) // Check if flag was reset (button not pressed).
{
printf("Interrupt 2 ");
}
}
Program – Send a character ‘*’ to the serial port regularly and for every specified delay
send a character ‘#’ to the serial port. Use timer interrupt.
#include<iolpc2148.h>
#include"intrinsics.h"
#include<stdio.h>
void TIMER0_ISR(void);
void main()
{
VPBDIV=0x01; //Set Baudrate as 9600bps
U0LCR=0x83;
U0DLL=0x4E;
U0DLM=0x00;
U0LCR=0x03;
PINSEL0=0x00000005;
117
Embedded System
__enable_interrupt();
while(1)
{
printf("*");
}
}
#pragma vector=0x18
__irq __arm void IRQ_ISR_Handler (void)
{
void (*interrupt_function)();
unsigned int vector;
static unsigned int us_count;
us_count++;
vector = VICVectAddr; // Get interrupt vector.
interrupt_function = (void(*)())vector; // Call MM_TIMER0_ISR thru pointer
(*interrupt_function)(); // Call vectored interrupt function
VICVectAddr = 0; // Clear interrupt in VIC
}
void TIMER0_ISR(void)
{
printf("#");
T0TC=0;
T0IR = 1; // Clear timer interrupt
}
118
Embedded System
int putchar(int c)
{
U0THR =c;
while((U0LSR&0x20)!=0x20);
return c;
}
Program - Blink the LED normally and if there is an interrupt occurred through serial
port switch on the other LED to indicate that the interrupt has occurred
#include "iolpc2148.h"
#include "intrinsics.h"
void SerialISR(void);
void delay();
unsigned char s;
void main()
{
VPBDIV=1; //PCLK=CCLK
U0LCR = 0x83; //DLAB=1,8-data bits
U0DLL = 0x4E;
U0DLM = 0x00; //Set Baudrate as 9600bps
U0LCR = 0x01;
U0IER = 0x00000001; //UART0 Interrupt Enable Register
PINSEL0 = 0x00000005; //Enable Transmit line
while(1)
{
IO0DIR=0x00030000;
IO0SET=0x00030000;
delay();
IO0CLR=0x00030000;
119
Embedded System
delay();
}
}
void SerialISR(void)
{
s=U0RBR;
IO0DIR=0x00030000;
IO0SET=0x00010000;
IO0CLR=0x00020000;
delay();
}
void delay()
{
int m,n;
for(m=0;m<100;m++)
{
for(n=0;n<1000;n++);
}
}
#pragma vector=0x18
__irq __arm void IRQ_ISR_Handler (void)
{
void (*interrupt_function)();
unsigned int vector;
vector = VICVectAddr;
interrupt_function = (void(*)())vector;
(*interrupt_function)();
VICVectAddr = 0;
}
Interrupts are used to ensure adequate service response times by the processing.
Sometimes, with software polling routines, service times by the processor cannot be
guaranteed, and data may be lost. The use of interrupts guarantees that the processor will
service the request within a specified time period, reducing the likelihood of lost data.
120
Embedded System
Most of the signals directly encountered in science and engineering are continuous: light
intensity that changes with distance; voltage that varies over time; a chemical reaction rate that
depends on temperature, etc. Analog-to-Digital Conversion (ADC) and Digital-to-Analog
Conversion (DAC) are the processes that allow digital computers to interact with these everyday
signals. Digital information is different from its continuous counterpart in two important respects:
it is sampled, and it is quantized. Digital systems are designed to store, process, and
communicate information in digital form. A digital system uses discrete (that is, discontinuous)
values to represent information for input, processing, transmission, storage, etc. The word
digital comes from the same source as the word digit and digitus (the Latin word for finger), as
fingers are used for discrete counting.
Digital Vs Analog
Analog signals were used in conjunction with copper telephone lines to transmit
conversations. This involved using 2 conductors for each line (send and receive). As technology
progressed an increasing number of people started using the telephone making analog signals
too expensive and troublesome to maintain. The pictures given below show the analog and
digital waveforms.
The X and Y lines represent the maximum voltage capacity for the signal to travel
clearly. The signal level crosses over the X and Y limits and has now become degraded and
hard for the device on the receiving end to interpret. The signals above and below X and Y lines
are called as “Noise”. Certain factors will add more "noise" to the signal are air conditioning
units, fluorescent lights, magnetic fields, etc. There are methods of separating or "filtering" noise
from analog signals. However, most of these methods are not accurate, or are devices that
transform the signals from analog to digital and back to analog. For these reasons, the use of
digital signaling is used to provide a better delivery method. Since the digital signal is very
uniform, noise has not severely altered its shape or amplitude. The digital signal shows a far
less change to the actual waveform than the previous analog signal. Computers use digital
signals to send and receive data. Although digital signals can only be in the state 1 (on) and 0
(off), complicated combinations of these two values are used to send/receive data.
121
Embedded System
Analog to Digital converter (ADC) is a device that converts continuously varying analog
signals from instruments that monitor such conditions as movement, temperature, sound, etc.,
into binary code for the computer. It may be contained on a single chip or can be one circuit
within a chip. Analog to Digital conversion is the process of changing continuously varying data,
such as voltage, current, or shaft rotation, into discrete digital quantities that represent the
magnitude of the data compared to a standard or reference at the moment the conversion is
made. According to the method of conversion ADCs can be classified into Direct-Conversion
ADCs, Successive Approximation ADCs, Integrating ADC and Sigma-Delta ADCs.
Direct-conversion ADCs: Direct conversion is also known as a flash conversion. ADCs based
on this architecture are extremely fast with a sampling rate of up to 1GHz. However, their
resolution is limited because of the large number of comparators and reference voltages
required. The input signal is fed simultaneously to all comparators. A priority encoder generates
a digital output that corresponds with the highest activated comparator. The identity of
comparators is important; any mismatch can cause a static error. Flash ADCs have a short
aperture interval - the time when the comparators' outputs are latched.
122
Embedded System
Integrating ADCs are extremely slow devices with low input bandwidths. But their ability to reject
high-frequency noise and fixed low frequencies such as 50Hz or 60Hz makes them useful in
noisy industrial environments and applications. Provide 10-18 bit resolution. A conversion time
for a medium speed 12 bit integrating ADC is about 20mS. This type of ADC is most commonly
used in multi-meters.
123
Embedded System
The modulator, whose architecture is similar to that of a dual-slope ADC, includes an integrator
and a comparator with a feedback loop that contains a 1-bit DAC. The modulator oversamples
the signal, transforming it to a serial bit stream with a frequency well above the required
sampling rate. The output filter then converts the bit stream to a sequence of parallel digital
words at the sampling rate. The delta-sigma converters perform high-speed, low resolution (1-
bit) A/D conversions, and then remove the resulting high-level quantization noise by passing the
signal through analog and digital filters. Features: high resolution, high accuracy, low noise, low
cost. Good for applications with a bandwidth up to 1MHz, such as speech, audio.
The LPC 2148 has 10-bit successive approximation analog to digital converter. Basic
clocking for the A/D converters is provided by the VPB clock. A programmable divider is
included in each converter, to scale this clock to the 4.5 MHz (max) clock needed by the
successive approximation process. A fully accurate conversion requires 11 of these clocks. The
ADC cell can measure the voltage on any of the ADC input signals. Note that these analog
inputs are always connected to their pins, even if the Pin function Select register assigns them
to port pins. A simple self-test of the ADC can be done by driving these pins as port outputs.
While the ADC pins are specified as 5 V tolerant More than 3.3 V (VDDA) +10 % should
not be applied to any pin that is selected as an ADC input, or the ADC reading will be incorrect.
If for example AD0.0 and AD0.1 are used as the ADC0 inputs and voltage on AD0.0 = 4.5 V
while AD0.1 = 2.5 V, an excessive voltage on the AD0.0 can cause an incorrect reading of the
AD0.1, although the AD0.1 input voltage is within the right range.
124
Embedded System
SEL - Selects which of the AD0.7:0/AD1.7:0 pins is (are) to be sampled and converted. For
AD0, bit 0 selects Pin AD0.0, and bit 7 selects pin AD0.7.
CLKDIV - The VPB clock (PCLK) is divided by (this value plus one) to produce the clock for the
A/D converter, which should be less than or equal to 4.5 MHz. Typically, software should
program the smallest value in this field that yields a clock of 4.5 MHz or slightly less.
BURST
1 The AD converter does repeated conversions at the rate selected by the CLKS field,
scanning (if necessary) through the pins selected by 1s in the SEL field. The first
conversion after the start corresponds to the least-significant 1 in the SEL field, then
higher numbered 1-bits (pins) if applicable. Repeated conversions can be terminated by
clearing this bit, but the conversion that’s in progress when this bit is cleared will be
completed.
(Important: START bits must be 000 when BURST = 1 or conversions will not start.)
0 Conversions are software controlled and require 11 clocks.
CLKS - This field selects the number of clocks used for each conversion in Burst mode, and the
number of bits of accuracy of the result in the RESULT bits of ADDR, between 11 clocks (10
bits) and 4 clocks (3 bits).
000 11 clocks / 10 bits
001 10 clocks / 9bits
125
Embedded System
RESULT - When DONE is 1, this field contains a binary fraction representing the voltage on the
Ain pin selected by the SEL field, divided by the voltage on the VDDA pin (V/VREF). Zero in the
field indicates that the voltage on the Ain pin was less than, equal to, or close to that on VSSA,
while 0x3FF indicates that the voltage on Ain was close to, equal to, or greater than that on
VREF.
CHN - These bits contain the channel from which the RESULT bits were converted (e.g. 000
identifies channel 0, 001 channel 1...).
OVERUN - This bit is 1 in burst mode if the results of one or more conversions was (were) lost
and overwritten before the conversion that produced the result in the RESULT bits. This bit is
cleared by reading this register.
DONE - This bit is set to 1 when an A/D conversion completes. It is cleared when this register is
read and when the ADCR is written. If the ADCR is written while a conversion is still in progress,
this bit is set and a new conversion is started.
126
Embedded System
BURST
1 The AD converters do repeated conversions at the rate selected by their CLKS fields,
scanning (if necessary) through the pins selected by 1s in their SEL field. The first
conversion after the start corresponds to the least-significant 1 in the SEL field, then
higher numbered 1-bits (pins) if applicable. Repeated conversions can be terminated by
clearing this bit, but the conversion that’s in progress when this bit is cleared will be
completed.
Important: START bits must be 000 when BURST = 1 or conversions will not start.
0 Conversions are software controlled and require 11 clocks.
START - When the BURST bit is 0, these bits control whether and when an A/D conversion is
started:
000 No start (this value should be used when clearing PDN to 0).
001 Start conversion now.
010 Start conversion when the edge selected by bit 27 occurs on P0.16 pin.
011 Start conversion when the edge selected by bit 27 occurs on P0.22 pin.
100 Start conversion when the edge selected by bit 27 occurs on MAT0.1.
101 Start conversion when the edge selected by bit 27 occurs on MAT0.3.
110 Start conversion when the edge selected by bit 27 occurs on MAT1.0.
111 Start conversion when the edge selected by bit 27 occurs on MAT1.1.
EDGE - This bit is significant only when the START field contains 010-111. In these cases:
1 Start conversion on a falling edge on the selected CAP/MAT signal.
0 Start conversion on a rising edge on the selected CAP/MAT signal.
The A/D Status register allows checking the status of all A/D channels simultaneously.
DONE0 - This bit mirrors the DONE status flag from the result register for A/D channel 0.
DONE1 - This bit mirrors the DONE status flag from the result register for A/D channel 1.
DONE2 - This bit mirrors the DONE status flag from the result register for A/D channel 2.
DONE3 - This bit mirrors the DONE status flag from the result register for A/D channel 3.
DONE4 - This bit mirrors the DONE status flag from the result register for A/D channel 4.
DONE5 - This bit mirrors the DONE status flag from the result register for A/D channel 5.
DONE6 - This bit mirrors the DONE status flag from the result register for A/D channel 6.
DONE7 - This bit mirrors the DONE status flag from the result register for A/D channel 7.
OVERRUN0 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 0.
OVERRUN1 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 1.
127
Embedded System
OVERRUN2 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 2.
OVERRUN3 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 3.
OVERRUN4 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 4.
OVERRUN5 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 5.
OVERRUN6 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 6.
OVERRUN7 - This bit mirrors the OVERRRUN status flag from the result register for A/D
channel 7.
ADINT - This bit is the A/D interrupt flag. It is one when any of the individual A/D channel Done
flags is asserted and enabled to contribute to the A/D interrupt via the ADINTEN register.
This register allows control over which A/D channels generate an interrupt when a conversion is
complete.
ADINTEN0
0 Completion of a conversion on ADC channel 0 will not generate an interrupt.
1 Completion of a conversion on ADC channel 0 will generate an interrupt.
ADINTEN1
0 Completion of a conversion on ADC channel 1 will not generate an interrupt.
1 Completion of a conversion on ADC channel 1 will generate an interrupt.
ADINTEN2
0 Completion of a conversion on ADC channel 2 will not generate an interrupt.
1 Completion of a conversion on ADC channel 2 will generate an interrupt.
ADINTEN3
0 Completion of a conversion on ADC channel 3 will not generate an interrupt.
1 Completion of a conversion on ADC channel 3 will generate an interrupt.
ADINTEN4
0 Completion of a conversion on ADC channel 4 will not generate an interrupt.
1 Completion of a conversion on ADC channel 4 will generate an interrupt.
ADINTEN5
0 Completion of a conversion on ADC channel 5 will not generate an interrupt.
1 Completion of a conversion on ADC channel 5 will generate an interrupt.
ADINTEN6
0 Completion of a conversion on ADC channel 6 will not generate an interrupt.
1 Completion of a conversion on ADC channel 6 will generate an interrupt.
ADINTEN7
0 Completion of a conversion on ADC channel 7 will not generate an interrupt.
1 Completion of a conversion on ADC channel 7 will generate an interrupt.
128
Embedded System
ADGINTEN
0 Only the individual ADC channels enabled by ADINTEN7:0 will generate interrupts.
1 Only the global DONE flag in ADDR is enabled to generate an interrupt.
The A/D Data Register hold the result when an A/D conversion is complete, and also include the
flags that indicate when a conversion has been completed and when a conversion overrun has
occurred.
RESULT - When DONE is 1, this field contains a binary fraction representing the voltage on the
AIN pin, divided by the voltage on the VREF pin (V/VREF). Zero in the field indicates that the
voltage on the AIN pin was less than, equal to, or close to that on VSSA, while 0x3FF indicates
that the voltage on AIN was close to, equal to, or greater than that on VREF.
OVERRUN - This bit is 1 in burst mode if the results of one or more conversions was (were) lost
and overwritten before the conversion that produced the result in the RESULT bits. This bit is
cleared by reading this register.
DONE - This bit is set to 1 when an A/D conversion completes. It is cleared when this register is
read.
Program – Convert the Analog value interfaced with channel 1 and 2 into digital and
display the result in the serial port
#include "iolpc2148.h"
#include<stdio.h>
void delay();
long int ADC1,ADC2;
void main()
{
VPBDIV = 0x01;
U0LCR = 0x83; //Uart0 Line Control Register, 8-bit data, DLAB=1
U0DLL=0x4E; //U0DLL: UART0 Divisor Latch (LSB),9600 bps
U0DLM=0x00; //U0DLM: UART0 Divisor Latch (MSB).
U0LCR=0x03;
PINSEL0=0x00000005;
PINSEL1=0x05000000; //Select P0.28 as AD0.1
AD0CR_bit.CLKDIV = 0x02; //This value loaded to select the clock for A/D.
(1200000/(2+1) must be less than 4.5 MHz)
129
Embedded System
AD0CR_bit.SEL = 0x04;
ADC2 = (AD0DR2 >> 6)&0x3FF; //6 to 15 bits are ADC result
PINSEL0=0x00000001;
printf(" CH1=%lx",ADC2);
printf("*");
goto loop;
}
int putchar(int c)
{
U0THR=c;
while((U0LSR&0x20)!=0x20);
return c;
}
void delay()
{
int i;
for(i=0;i<1000;i++);
}
130
Embedded System
Example
Input: A binary word 100101112 (=15110)
Output: Analog signal representing the weighted sum of the non- zero bits in the word.
Example: 2.96 Volts
Binary weighted resistor network: The binary weighted resistor network Comprises of a
register and resistor network. The output of each bit of the register will depend on whether a 1
or a 0 is stored in that position
e.g. for a 0 then 0V output
for a 1 then 5V output
Resistance R is inversely proportional to binary weight of each digit
R I1 Rf
MSB
4-bit register
2R I2 If
4R -
I3 S I
LSB 8R I4 +
Vo
Vo = − If R f = −( I1 + I2 + I3 + I 4 ) Rf
This is very difficult to manufacture.
R-2R Ladder Resistor Network: The R-2R Ladder Resistor Network has a resistor network
which requires resistance values that differ 2:1 for any sized code word. The principle of the
network is based on Kirchhoff’s current rule.
131
Embedded System
I R R R
Vs 2R 2R 2R 2R 2R
Rf
+
Vo
4-bit register
MSB
LSB
Vo = -R f ( b 3 I 2 + b2 I 4 + b1 I 8 + b 0 I 16)
Fig.18.2: R-2R Ladder Network
DAC Register (DACR - address 0xE006 C000) - This read/write register includes the digital
value to be converted to analog, and a bit that trades off performance vs. power. Bits 5:0 are
reserved for future, higher-resolution D/A converters.
VALUE: After the selected settling time after this field is written with a new VALUE, the voltage
on the AOUT pin (with respect to VSSA) is VALUE/1024 * VREF.
BIAS:
0 The settling time of the DAC is 1 µs max, and the maximum current is 700 υA.
1 The settling time of the DAC is 2.5 µs and the maximum current is 350 µA.
#include<iolpc2148.h>
132
Embedded System
/* Initialize DAC */
PINSEL1=0x00040000;
while ( 1 )
{
DACR = (i << 6) | DAC_BIAS;
i++;
if ( i == 1024 )
{
i = 0;
}
}
return 0;
}
DAC Applications
133
Embedded System
19 SENSOR INTERFACING
134
Embedded System
Smoke Sensor
The fire detection is one of the major precaution system in industry, because significant
loss to business occurs through fires in the workplace. Whether large or small, fire causes
personal suffering, damage to plant, equipment and buildings, and loss of business. The
automatic fire detection system provides the following features:
❖ Fire avoidance - in personnel, downtime and repair costs
❖ Automated process - Saves costs and man-hours
❖ Improved industry safety
❖ Higher confidence in safety of material
Smoke detectors are one of those amazing inventions that, because of mass production,
cost practically nothing. And while they cost very little, smoke detectors save thousands of lives
each year. In fact, it is recommended that every home have one smoke detector per floor.
The two most common types of smoke detectors used today: photoelectric detectors and
ionization detectors. The photoelectric detectors are work as photoelectric diodes. Which
senses the lack of light and triggers. The problems of photoelectric detectors are
o It's a pretty big smoke detector.
o It is not very sensitive.
135
Embedded System
the chamber. To "ionize" means to "knock an electron off of." When you knock an electron off of
an atom, you end up with a free electron (with a negative charge) and an atom missing one
electron (with a positive charge). The negative electron is attracted to the plate with a positive
voltage, and the positive atom is attracted to the plate with a negative voltage (opposites attract,
just like with magnets). The electronics in the smoke detector sense the small amount of
electrical current that these electrons and ions moving toward the plates represent. When
smoke enters the ionization chamber, it disrupts this current -- the smoke particles attach to the
ions and neutralize them. The smoke detector senses the drop in current between the plates
and sets off the horn.
-12V
+12v
U1A
11
R1
U2B
R2
4
2 -
R4
1 5 1k
+
3 + 7
100k 6 To Microcontroller
1k -
4 TL034 D1
11
TL034 R6
R3
VCC +12V 1k 100k
POT
-12v 3.3k 1k
VCC
+12v
100k
POT
SMOKE SENSOR R5
470 ohm
R7 +12v
POT
Proximity Sensor
136
Embedded System
20 VEEPRO
The goal of this chapter is to be able to write a short program, which accepts the inputs
(frequency, power level etc) from the user, processes them, communicate with the
measurement equipments, retrieve the measured raw data from these equipments, analyze
data and presents the user in meaningful forms. The concept of VEE programming resembles
that of program flow chart. A box represents each instruction or I/O operation. Boxes are in
turns connected with data flow paths (wires).
Agilent VEE Pro interacts with the world. It interfaces with popular office tools: use
Microsoft® Word for reports, Excel for spreadsheets, Outlook for paging and e-mail, and Access
for database operations. Agilent VEE Pro integrates the .NET Framework and ActiveX,
simplifying common tasks and making powerful system capabilities available to your programs.
Now it is easy to complete tasks such as programmatically managing files, sending an email
report, or invoking a web page.
Agilent VEE Pro supports industry-standard instrument drivers including IVI-COM and
VXI plug & play as well as a variety of legacy drivers. If an industry-standard driver is not
available, use the .dll library supplied with many instruments and PC Cards. In addition to GPIB
connectivity, Agilent VEE Pro allows you to connect directly to LAN and USB enabled
instruments using industry-standard protocols. VXI, PC plug-ins and other back-planes can be
controlled from Agilent VEE Pro.
MATLAB® Script and The MathWorks Signal Processing Toolbox as well as the
Microsoft .NET Framework Library are embedded in Agilent VEE Pro, included at no extra cost.
With MATLAB Script and The MathWorks Signal Processing Toolbox embedded in Agilent VEE
Pro, you get 500 of the most popular MATLAB analysis and visualization functions
preprogrammed as one-click objects in Agilent VEE Pro. Without leaving Agilent VEE Pro, you
can instantly transform your measurement data into usable information. Built-in MATLAB
functions include:
• Numeric computation
• Engineering & scientific graphics (2D, 3D, waterfall, bar, pie)
• Signal processing
137
Embedded System
Software requirements
• Microsoft Windows® 98 SE, Windows ME, Windows NT 4.0 with service pack
6a,Windows 2000 with service pack 4, or Windows XP with service pack 1
PC Hardware requirements
Example
The following program and figure compare a simple function programmed first in a textual
language (ANSI C) and then in VEE. In both cases, the function creates an array of 10 random
numbers, finds the maximum value, and displays the array and maximum value.
#include"iolpc2148.h"
#include<stdio.h>
#include <math.h>
main( )
{
double num[10],max;
int i;
for (i=0;i<10;i++)
{
num[i]=(double)rand()/pow(2.0,15.0);
printf("%f ",num[i]);
}
max=num[0];
for (i=1;i<10;i++)
138
Embedded System
{
if (num[i]>max)max=num[i];
}
printf("/nmax; %f/n",max);
}
In VEEPRO, the program is built with program elements called objects. Objects are the
building blocks of a VEE program. They perform various functions such as I/O operations,
analysis, and display. In VEE, data moves from one object to the next object in a consistent
way: data input on the left, data output on the right, and operational sequence pins on the top
and bottom.
Objects
A VEE program consists of the objects in the work area and the lines that connect them.
The lines that connect VEE objects are connected between object pins. Each object has several
pins. Here, the Formula object is used as an example. You can use any object.
139
Embedded System
Connect the data input and output pins to carry data between objects. The sequence pin
connections are optional. If connected, they will dictate an execution order.
Select Start > Programs > Agilent VEE Pro to load the program. You will see the main
screen window where you can start writing the program as in figure.
A VEE program consists of connected objects. To create a program, select objects from
VEE menus, such as Flow, Data, and Display. Connect the objects via lines that attach to the
object pins.
Pull down an appropriate menu, click the desired object, drag the object to an
appropriate location in the work area, and click (the outline will disappear and the object will
appear). For example, to add a Function Generator object to the work area, select Device
Virtual Source -> Function Generator in the menu bar as shown in following figure. An outline of
the object appears in the work area.
140
Embedded System
The arrow to the right of Virtual Source indicates a submenu. Three dots after a menu item
indicate that one or more dialog boxes will follow. For example, File Save As... operates this
way.
Move the Function Generator to the center of the work area, and click to place the object. The
Function Generator appears.
141
Embedded System
VEE displays objects either in “icon view” or “open view”. The iconic view conserves space in
the work area and makes programs more readable.
Icon View
Each VEE object has an object menu that lets you perform actions on the object, such as Clone,
Size, Move, and Minimize. Most objects have similar attributes, but there are differences,
depending on the functionality of the object.
1. To select the object menu, click once on the object menu button. (All object menus open the
same way.) The object menu appears, as follows. (Do not double-click the object menu button.
That is the shortcut for deleting the object.)
2. Now you can click one of the object menu choices to perform the action you desire. Or, to
dismiss the menu, click an empty area outside the menu.
1. Open the object menu and select Properties... A Properties window appears on the left side
of your screen. Select the property and change the property value to whatever you would like.
1. Click on or just outside the data output pin of one object, then click on the data input pin of
another, as shown below (A line appears behind the pointer as you move from one pin to the
other.)
142
Embedded System
2. Release the cursor and VEE draws a line between the two objects. Notice that if you
reposition the objects, VEE maintains the line between them.
Press Shift-Ctrl and click the line you want to delete. (OR)
Select Edit - Delete Line and click the line you want to delete.
Adding a Terminal
You can add terminals to an object. For example, you can add a second data input terminal to
the Formula object. Open the object menu and select Add Terminal - Data Input. (OR) With
Show Terminals turned on, you can place the mouse pointer in the “terminal area” (the left
margin of the open view object) and press Ctrl+A (press the Ctrl and A keys simultaneously).
143
Embedded System
Deleting a Terminal
Open the object menu and select Delete Terminal Input... or Delete Terminal Output, choose
the input or output to delete, and click OK. For example, following figure shows the dialog box
that appears when you choose Delete Terminal Input....
-OR-
Place the mouse pointer over the terminal and press CTRL-D.
You can loop (repeat) part of your VEE program using one of the repeat objects described in the
following list. You can include the Next and Break objects in a loop "hosted" by any of these
objects. These are all under the Flow Repeat menu. The loop objects are
For Count, For Range, For Log Range, For Each, Until Break, On Cycle, Next, Break
The Instrument Manager toolbar allows you to find and add instruments, load sample
programs, save and print IO configuration file, restore to saved I/O configuration, open help
topics, and create I/O objects. Select I/O Instrument Manager to display the Instrument Manager
tool window. Use this tool window to add, delete, edit, and configure interfaces and instruments.
You can also create the following types of instrument I/O objects: Direct I/O, IVI-COM Drivers,
NIDAQ Drivers, VXI plug & play Drivers, Panel Drivers, and Component Drivers. Use Advanced
I/O to access objects for low-level control of the GPIB, RS-232 (serial), VXI, LAN, and USB
interfaces (such as bus commands, polling, and service requests). The Advanced Instrument
Properties dialog box provides the interface configurations.
Examples
Apple Bagger
You want to know how many apples it takes to fill a ten pound basket. Create a VEE
program that counts how many apples it takes to fill the basket. Each apple weighs between 0
and 1 pound.
144
Embedded System
Create a program that generates 100 random numbers and displays them. Record the total time
required to generate and display the values.
145
Embedded System
Testing Numbers
Create a program that allows a user to enter a number between 0 and 100. If the number is
greater than or equal to 50, display the number. If it is less than 50, display a pop-up box with
the message “Please enter a number between 50 and 100.”
MATLAB in VEE
VEE is shipped with the MATLAB® Script engine, which gives users direct access to the
core set of MATLAB functionality, such as advanced mathematics, data analysis, and scientific
and engineering graphics. The MATLAB Script is only a subset of the standard, full-featured
MATLAB from The MathWorks. If you have a full-featured MATLAB installed on your machine,
then it is easy to use the full power of the MATLAB in VEE programs.
146
Embedded System
3. Under the MATLAB tab, click the MATLAB version you want to use.
4. Click the Save button, this will close the Default Preferences dialog box.
5. Save your current VEE program and restart the Agilent VEE.
Please note that after changing the MATLAB used in the Default Preferences dialog box,
you must save the change and restart the Agilent VEE to let the changing take effect.
MATLAB® Script
Matlab Script is an object that calls the MATLAB Script engine with operations specified
by MATLAB Script commands. VEE data can be passed to the MATLAB Script engine and
returned from the MATLAB Script engine. The Help topic you are reading describes how to
invoke MATLAB from VEE. It does not explain how to write MATLAB programs or what you can
do with MATLAB once you have invoked it. Help on MATLAB and its scripting language is
available two ways:
VEE’s Function & Object Browser has a Help button at the bottom. Clicking the Help
button when you have a MATLAB function selected starts the MATLAB Help system and
displays the topic for that function. The MATLAB object menu (right-click menu) contains a
MATLAB Help choice. (Note: "Help" and "MATLAB Help" are both on this menu.) Clicking
MATLAB Help starts the MATLAB Help system. If your MATLAB Script object was created from
VEE’s Device menu, the help system is started with the main MATLAB HelpDesk window. If
your MATLAB Script object was created from VEE’s Function & Object Browser, the help
system is started with the topic for the function you selected when you created the MATLAB
Script object.
Use
Use the MATLAB Script object to access the power of MATLAB software within VEE.
This object is similar to a VEE Formula object. MATLAB Script commands can be entered in the
formula field, and data can be passed using input and output pins. Many predefined functions
are available when you create a MATLAB Script object from the Function & Object Browser.
Alternately, the default object available from the Device menu has two inputs, one output, and
an example script (X=A+B). Any of these example objects can be modified to have a different
number of input or output pins and a different set of MATLAB Script commands. There are
approximately 1800 functions available in the MATLAB Script engine supplied with VEE. The
MATLAB Signal Processing Toolkit provides about 220 more functions. VEE's Function &
Object Browser shows more than 1100 of the most popular functions. Consult the MATLAB
HelpDesk for information about all the MATLAB functions.
Variable names in MATLAB Script are case sensitive, but not so in VEE. In other words,
"A" and "a" refer to the same variable in VEE, but refer to different variables in MATLAB. Keep
this in mind when writing formulas in MATLAB Script. For example, if your VEE data terminal is
named "A", use "A" in the MATLAB Script, not "a". VEE does not perform any syntax checking
of MATLAB Script commands. If your MATLAB Script object contains syntax errors, those errors
are not discovered until the MATLAB Script engine is called. If MATLAB reports any warnings,
these are shown as VEE Caution messages.
147
Embedded System
The first MATLAB Script object to execute opens a single MATLAB session. All other
instances of MATLAB Script objects share that same session. Therefore, MATLAB Script
objects can share global variables in the MATLAB workspace. MATLAB Script, as provided by
this VEE object, does not support the MATLAB function definition capability.
Data Notes
Only some VEE data types are allowed as MATLAB Script inputs. You can use input
terminal data type constraints to ensure that VEE input data is converted to a supported type.
For example, assume you have Int32 data. The MATLAB Script object does not accept integer
data, but it accepts Real64 data. You can double-click the input terminal and select Real64 as
the Required Type. With that constraint set, inbound Int32 data is automatically promoted to
Real64 by the input pin before it is passed to MATLAB. VEE also provides some automatic
array conversions to increase the convenience of using VEE 1D arrays. The following tables
describe the alignment of VEE data types and MATLAB data types.
To MATLAB
From VEE Type Notes
Type
Text Scalar character array Promoted to array size (1 x n), where n is the
length of the VEE string.
Text 1D Array character array Becomes array size (m x n), where m is the
number of elements in the VEE array and n is
the length of the longest VEE string in the array.
Text Array, 2D or more -- Not supported.
Real64 Scalar double array Promoted to array size (1 x1).
Real64 Array double array VEE 1D arrays are promoted to array size (m x
1). VEE arrays with 2D or greater retain original
shape.
Complex Scalar complex array Promoted to array size (1 x 1).
Complex Array complex array VEE 1D arrays are promoted to array size (m x
1). VEE arrays with 2D or greater retain original
shape.
Waveform 1D Array double array VEE 1D arrays are promoted to array size (m x
1). Waveform time-base mapping is lost.
148
Embedded System
MATLAB Script allows (and sometimes generates) infinity as a numeric value. VEE does
not allow values of infinity.
VEE includes the MATLAB Script object, which gives you access to the functionality of
MATLAB. VEE can pass data to the MATLAB Script Engine and receive data back, enabling
you to include MATLAB mathematical functions in VEE programs.
Following figure shows how a MATLAB Script object appears in a VEE program. When
this program executes, it generates the data shown in the Alphanumeric object.
149
Embedded System
This figure shows the graph that is produced when the program runs.
When you include MATLAB Script objects in a VEE program, VEE calls the MATLAB
Script Engine to perform the operations in the MATLAB Script objects. Information is passed
from VEE to MATLAB and back again.
150
Embedded System
21 RTOS FUNDAMENTALS
To most people, embedded systems are not recognizable as computers. Instead, they
are hidden inside everyday objects that surround us and help us in our lives. Embedded
systems typically do not interface with the outside world through familiar personal computer
interface devices such as a mouse, keyboard and graphic user interface. Instead, they interface
with the outside world through unusual interfaces such as sensors, actuators and specialized
communication links.
RTOS Fundamentals
151
Embedded System
The most basic category of kernel services, at the very center of Figure, is Task
Management. This set of services allows application software developers to design their
software as a number of separate "chunks" of software -- each handling a distinct topic, a
distinct goal, and perhaps its own real-time deadline. Each separate "chunk" of software is
called a "task." Services in this category include the ability to launch tasks and assign priorities
to them. The main RTOS service in this category is the scheduling of tasks as the embedded
system is in operation. The Task Scheduler controls the execution of application software tasks,
and can make them run in a very timely and responsive fashion.
Many (but not all) RTOS kernels provide Dynamic Memory Allocation services. This
category of services allows tasks to "borrow" chunks of RAM memory for temporary use in
application software. Often these chunks of memory are then passed from task to task, as a
means of quickly communicating large amounts of data between tasks. Some very small RTOS
kernels that are intended for tightly memory-limited environments, do not offer Dynamic Memory
Allocation services. Many (but not all) RTOS kernels also provide a "Device I/O Supervisor"
category of services. These services, if available, provide a uniform framework for organizing
and accessing the many hardware device drivers that are typical of an embedded system.
In addition to kernel services, many RTOSs offer a number of optional add-on operating
system components for such high-level services as file system organization, network
communication, network management, database management, user-interface graphics, etc.
Although many of these add-on components are much larger and much more complex than the
RTOS kernel, they rely on the presence of the RTOS kernel and take advantage of its basic
services. Each of these add-on components is included in an embedded system only if its
services are needed for implementing the embedded application, in order to keep program
memory consumption to a minimum.
Many non-real-time operating systems also provide similar kernel services. The key
difference between general-computing operating systems and real-time operating systems is
the need for " deterministic " timing behavior in the real-time operating systems. Formally,
"deterministic" timing means that operating system services consume only known and expected
amounts of time. In theory, these service times could be expressed as mathematical formulas.
These formulas must be strictly algebraic and not include any random timing components.
Random elements in service times could cause random delays in application software and could
then make the application randomly miss real-time deadlines – a scenario clearly unacceptable
for a real-time embedded system.
152
Embedded System
On the other hand, real-time operating systems often go a step beyond basic
determinism. For most kernel services, these operating systems offer constant load-
independent timing: In other words, the algebraic formula is as simple as: T(message_send) =
constant , irrespective of the length of the message to be sent, or other factors such as the
numbers of tasks and queues and messages being managed by the RTOS.
Task scheduling
What if a low-priority task has already begun to run, and then a higher-priority task
becomes ready? This might occur because of an external world trigger such as a switch closing.
A priority-based preemptive scheduler will behave as follows: It will allow the low-priority task to
complete the current assembly-language instruction that it is executing. [But it won’t allow it to
complete an entire line of high-level language code; nor will it allow it to continue running until
the next clock tick.] It will then immediately stop the execution of the low-priority task, and allow
the higher-priority task to run. After the higher-priority task has finished its current work, the low-
priority task will be allowed to continue running.
Of course, while the mid-priority task is running, an even higher-priority task might
become ready. This is represented in Figure 3 by "Trigger_2" causing the "High-Priority Task" to
become ready. In that case, the running task ("Mid-Priority Task") would be preempted to allow
the high-priority task to run. When the high-priority task has finished its current work, the mid-
priority task would be allowed to continue. And after both the high-priority task and the mid-
priority task complete their work, the low-priority task would be allowed to continue running. This
situation might be called "nested preemption."
153
Embedded System
Each time the priority-based preemptive scheduler is alerted by an external world trigger
(such as a switch closing) or a software trigger (such as a message arrival), it must go through
the following 5 steps:
Determine whether the currently running task should continue to run. If not …
Determine which task should run next.
Save the environment of the task that was stopped (so it can continue later).
Set up the running environment of the task that will run next.
Allow this task to run.
These 5 steps together are called "task switching."
In RTOS the task switching time is constant, independent of any load factor such as the
number of tasks in a software system. For a general-computing (non-real-time) operating
system, the task switching time generally rises as a software system includes more tasks that
can be scheduled.
154
Embedded System
Probably the most popular kind of communication between tasks in embedded systems is the
passing of data from one task to another. Most RTOSs offer a message passing mechanism for
doing this. Each message can contain an array or buffer of data. If messages can be sent more
quickly than they can be handled, the RTOS will provide message queues for holding the
messages until they can be processed.
RTOS is…
Responsibilities of RTOS
uC/OS-II
The most common RTOS include VxWorks, Windows CE, Palm, ucLinux, pSOS, uC/OS
etc.
155
Embedded System
156
Embedded System
C/OS-II Features
The Board Support Package (BSP) provides functions to encapsulate common I/O
access functions and make porting your application code easier. Essentially, these files are the
interface between the application and the target board. Though one file, bsp.c, contains some
functions, which are intended to be called directly by the user (all of which are prototyped in
bsp.h), the other files serve the compiler (as with cstartup.s79).
The BSP includes two files intended specifically for use with IAR EWARM v4.4x:
LPC2148_Flash.xcl and cstartup.s79. These serve to define the memory map and initialize the
processor prior to loading or executing code. If the example application is to be used with other
tool-chains, the services provided by these files must be replicated as appropriate. Before the
processor memories can be programmed, the compiler must know where code and data should
be placed. IAR requires a linker command file, such as LPC2148_Flash, that provides directives
to accomplish this. With this file, the data and execution stacks are mapped to RAM while code
is mapped to flash.
In cstartup.s79 is code, which will be executed prior to calling main. One important
inclusion is the specification of the exception vector table (as required for ARM cores) and the
setup of various exception stacks. After executing, this function branches to the IAR-specific
main function, in which the processor is further readied for entering application code.
157
Embedded System
C/OS-II Services
158
Embedded System
159
Embedded System
#include "includes.h"
OS_STK Task1stk[1000];
OS_STK Task2stk[1000];
OS_STK Task3stk[1000];
160
Embedded System
void main()
{
IO0DIR = 0X00030000;
IO1DIR = 0X00FF0000;
OSInit();
OSTaskCreate(Task1, NULL, &Task1stk[999], 1);
OSTaskCreate(Task2, NULL, &Task2stk[998], 2);
OSTaskCreate(Task3, NULL, &Task3stk[998], 3);
OSStart();
}
RTOS application software helps us to write application codes easier. The predefined
services of C/OS-II RTOS provide simple implementation of the tasks, which is hard in general
operating system.
161
Embedded System
22 EMBEDDED NETWORKING
The past few years have seen the beginning of a trend to dramatically increase the
embedded electronics content of automobiles, elevators, building climate control systems, jet
aircraft engines, and other traditionally electro-mechanically controlled systems. In many large
systems this increasing electronics content is being accompanied by a proliferation of
subsystems having separate CPUs. The increase in the number of processors in a system is
often driven by computation and I/O growth. In some development environments, the increase
may also be driven by a need to ease system integration burdens among multiple design groups
or to provide system flexibility through "smart sensors" and "smart actuators". But, whatever the
reasons, once there is more than one CPU in a system there must be some means of
communication to coordinate action. In this section we can learn the communication techniques,
which are commonly used in embedded applications.
Basics Of Networking
Communication is the transfer of information from one place to another. The need to
human being to communicate gave rise to various forms of communication techniques. The
majority of embedded communication systems can be classified as either point-to-point
networks or shared media networks. The process of communication involves the following three
components: Sender - the component from where the information is transferred, Receiver – the
component to which the information is transferred and the Medium – the component through
which the information is transferred. In case of embedded system the sender and receiver are
computers or microcontrollers. The medium through which the information is transferred may be
cables or other such physical media.
Basically, bus is a means of getting data from one point to another, one device to
another device or one device to multiple devices. The bus includes not only the actual capability
to transfer data between devices, but also all appropriate signaling information to insure
complete movement of data between the devices. The protocol is a set of rules that is instituted
between devices to allow for the orderly flow of information. Protocols include rules or
capabilities to support aspects such as when to send information, how to send it, how much
information can be sent, confirmation that information has been sent, and means of confirming
that the correct information has been sent. The protocol has the elements such as Flow control
mechanism to avoid loss of data, Synchronization technique to match the speeds of the device
and error-checking method for efficient data transfers. Depending on the complexity of the
information to be sent, protocol can be simple or very extensive.
162
Embedded System
Networking Applications
Essentials Of Networking
In practice, we have found that embedded real-time networks require high efficiency,
deterministic latency, operational robustness, configuration flexibility, and low cost per node.
• High Efficiency: To increase the network bandwidth the system must have higher
efficiency. For example, CSMA/CD is highly efficient for light traffic but gives poor
performance if heavily loaded
• Determinacy: It is the ability to calculate worst-case response time is important for
meeting the real-time which is fundamentally enabled by the media access protocol, is
highly desirable for many safety critical applications.
• Robustness: Many applications require robust operation under extreme conditions. We
call a protocol robust if it can quickly detect and recover from errors, added nodes, and
deleted nodes.
• Flexibility: For networking applications the protocol should allow range of devices for
sharing the information.
• Low cost: Simple protocols require less hardware and software resources and are
therefore likely to be less expensive. For extremely cost-sensitive high-volume
applications, these protocols are good candidates. However, for growth-expected
applications, more advanced protocols provide a stronger foundation.
Serial Protocols
One main aspect of a bus is whether the data is transferred in a serial or parallel fashion.
In serial mode, the bits of each character are transmitted one at a time, one after another.
Contrast with parallel transmission, where the bits of a character or data are transferred
simultaneously. The speed of a serial bus is generally expressed in bits per second (bps) and
the speed of the parallel bus is expressed in bytes per second (Bps) or characters per second.
The bits per second rate are also called as baud rate. When comparing with the parallel
interface, the number of wires is reduced to one or two in serial communication. The serial
approach is cost-effective, especially for long distances.
Both the serial and parallel communication has numerous modes of operation. They are:
• Simplex - The simplex mode uses a single channel or frequency to exchange
information between two or more terminals. Communications is in one direction only.
• Half Duplex - The half-duplex mode has one-way flow of information between terminals.
Technical arrangements often permit transmission in either direction, but not
simultaneously.
163
Embedded System
• Semi Duplex - The semi duplex uses an arrangement of equipment where one terminal
is simplex configured and the other uses two channels or frequencies in full duplex. A
clarifying example is a ship in a simplex mode terminated full duplex with a shore station.
The ship may send or receive but not do both at the same time.
• Full Duplex - The full-duplex mode is a method of operation in which
telecommunications between stations takes place simultaneously in both directions
using two separate frequencies. The term "full duplex" is synonymous with "duplex."
• Broadcast - Broadcast is the type of operation in which one station transmits
information on one or more channels directed to more than one station and/or unit. The
broadcast system has no provision for receipt or reply; however, special arrangements
may require the receiving station to reply or receipt for the message at a later time by
other means.
RS-232
The majority of computers equipped with a RS232 interface. The standard was updated
in 1969. It enables full-duplex link to be established between two devices. Since this standard
recommended by an American manufacturers organization called EIA (Electronics Industry
Association) it is generally called as Recommended Standard. RS232 is a point-to-point or
single ended approach. The input and output voltages are referenced to a common ground. The
driver output levels of a logic low are between 5V and 15V. Likewise, the driver logic high
specification is from –3V through –25V.
164
Embedded System
In addition to the data signals, the interface also includes control/status signals.
According to the standard the devices are split into two types – Data Terminal Equipment (DTE)
and Data Communication Equipment (DCE). The standard specifies male connectors for DTE
and female connectors for DCE. The data terminal ready (DTR), which emits positive voltage,
indicates that the DTE is ready for communication. Likewise, positive voltage at the output Data
Set Ready (DSR) manifests the readiness to exchange information. The data flow in a certain
direction is controlled by the signals Request to send (RTS) and Clear to send (CTS). Positive
voltage at the output RTS allows the DCE to send data to DTE. The same is valid for the output
CTS, which in turn, controls the data flow from the DTE to the DCE. The Data Carrier Detect
(CD) and the Ring Indicator (RI) lines are only available in connections to a modem. Carrier
Detect is used by a modem to signal that it has a made a connection with another modem, or
has detected a carrier tone. The last remaining line is RI or Ring Indicator. A modem toggles the
state of this line when an incoming call rings your phone.
The byte to be transmitted gets into a "transmit shift register" in the serial port. From this
shift register bits are taken from the byte one-by-one and sent out bit-by-bit on the serial line.
Then when the last bit has been sent and the shift register needs another byte to send it could
just ask the CPU to send it another byte. Thus we say that the serial port is interrupt driven.
Each time the serial port issues an interrupt; the CPU sends it another byte. Once a byte has
been sent to the transmit buffer by the CPU, then the CPU is free to pursue some other activity
until it gets the next interrupt. The serial port transmits bits at a fixed rate, which is selected by
the user. Receiving bytes by a serial port is similar to sending them only it's in the opposite
direction. It's also interrupt driven. For the obsolete type of serial port with 8-bit buffers, when a
byte is fully received from the external cable it goes into the 8-bit “receive buffer”.
The RS232 standard does not specify the baud rate, however it imposes limitation on
the transition time from one logic level to the other. The transition time must not exceed 4% of
one bit time. The resulting maximum cable length is restricted to 50 Feet for 19200 bps. The
external environment has a large effect on lengths for unshielded cables. In electrically noisy
environments, even very short cables can pick up stray signals. To achieve higher baud rates
for longer distance high-quality shielded cables must be used. To connect any RS232 to a
microcontroller system we must use converters such as MAX232. These converters are also
called as line drivers or RS232 buffers.
RS485
RS232 is without doubt the best-known interface, because this serial interface is
implemented on almost all computers available today. But some of the other interfaces are
certainly interesting because they can be used in situations where RS232 is not appropriate.
The RS485 system requires the designer to implement a more sophisticated method of error
detection, including methods such as line contention detection, acknowledgement of
transmissions and a system for resending corrupted data. RS485 is designed to connect DTE's
directly without the need of modems, to connect several DTE's in a network structure, to
communicate over longer distances and to communicate at faster communication rates. RS485
is the most versatile communication standard in the standard series defined by the EIA. RS485
is currently a widely used communication interface in data acquisition and control applications
where multiple nodes communicate with each other.
One of the main problems with RS232 is the lack of immunity for noise on the signal
lines. The transmitter and receiver compare the voltages of the data- and handshake lines with
one common zero line. Shifts in the ground level can have disastrous effects. Therefore the
165
Embedded System
trigger level of the RS232 interface is set relatively high at ±3 Volt. Noise is easily picked up and
limits both the maximum distance and communication speed. With RS485 on the contrary there
is no such thing as a common zero as a signal reference. Several volts difference in the ground
level of the RS485 transmitter and receiver does not cause any problems.
The RS485 signals are floating and each signal is transmitted over a Sig+ line and a Sig-
line. The RS485 receiver compares the voltage difference between both lines, instead of the
absolute voltage level on a signal line. This works well and prevents the existence of ground
loops, a common source of communication problems. The best results are achieved if the Sig+
and Sig- lines are twisted. An RS-485 receiver must see a voltage difference of just 200 mV
between Sig+ and Sig-. If Sig+ is at least 200 mV greater than Sig-, the receiver's output is logic
high. If Sig- is at least 200 mV greater than Sig+, the output is a logic low. For differences less
than 200 mV, the output is undefined. At the driver, the voltage difference must be at least 1.5
V, so the interface tolerates a fair amount of non-common mode noise and attenuation. RS-485
is designed to be wired in a daisy chain or bus topology. Any stubs that connect a node to the
line should be as short as possible. Most links use twisted pairs because of their ability to cancel
magnetically and electro magnetically coupled noise.
When a network needs to transfer small blocks of information over long distances, RS-
485 is often the interface of choice. The network nodes can be PCs, microcontrollers, or any
devices capable of asynchronous serial communications. Compared to Ethernet and other
network interfaces, RS-485's hardware and protocol requirements are simpler and cheaper. The
RS-485 standard is flexible enough to provide a choice of drivers, receivers, and other
components depending on the cable length, data rate, number of nodes, and the need to
conserve power. Twisting pair cable allows RS485 to communicate over much longer
communication distances than achievable with RS232. With RS485 communication distances of
1200 m are possible. Differential signal lines also allow higher bit rates than possible with non-
differential connections. Therefore RS485 can overcome the practical communication speed
limit of RS232. The maximum speed is 35Mbps for 12 meters and the speed is 100kbps for
1200 meters.
SPI is a serial bus standard established by Motorola and supported in silicon products
from various manufacturers. Both SPI and I2C provide good support for communication with
slow peripheral devices that are accessed intermittently. But SPI is better suited than I 2C for
applications that are naturally thought of as data streams (as opposed to reading and writing
addressed locations in a slave device). SPI can also achieve significantly higher data rates than
I2C. SPI-compatible interfaces often range into the tens of megahertz. SPI really gains efficiency
in applications that take advantage of its duplex capability, which consists of simultaneously
sending information in and out. SPI devices communicate using a master-slave relationship.
Due to its lack of built-in device addressing, SPI requires more effort and more hardware
resources than I2C when more than one slave is involved. But SPI tends to be simpler and more
efficient than I2C in point-to-point (single master, single slave) applications for the very same
reason; the lack of device addressing means less overhead.
SPI specifies four signals: clock (SCLK); master data output, slave data input (MOSI);
master data input, slave data output (MISO); and slave select (SS). SCLK is generated by the
master and input to all slaves. MOSI carries data from master to slave. MISO carries data from
slave back to master. A slave device is selected when the master asserts its SS signal.
166
Embedded System
If multiple slave devices exist, the master generates a separate slave select signal for
each slave. The master generates slave select signals using general-purpose discrete
input/output pins or other logic. SPI doesn't describe a specific way to implement multi-master
systems. If multiple slaves are used that are fixed in different configurations, the master will
have to reconfigure itself each time it needs to communicate with a different slave. SPI does not
have an acknowledgement mechanism to confirm receipt of data. In fact, without a
communication protocol, the SPI master has no knowledge of whether a slave even exists. SPI
also offers no flow control. If you need hardware flow control, you might need to do something
outside of SPI.
SPI's full duplex communication capability and data rates (ranging up to several
megabits per second) make it, in most cases, extremely simple and efficient for single master,
single slave applications. On the other hand, it can be troublesome to implement for more than
one slave, due to its lack of built-in addressing; and the complexity only grows as the number of
slaves increases. The original speed of the SPI is 110kHz. The maximum cable length of the
both SPI and I2C will not exceed 1 meters. The fast and flexible feature of the SPI
communication makes it used in applications such as consumer electronics,
telecommunications, industrial control and measurement equipments.
In recent years, the computer emerged as a number of peripherals in both business and
the home. The serial and parallel communication ports are not able to satisfy the demands for
performance and number of links. In order to solve the problem, experts from well known
companies Compaq, Digital Equipment Corporation (DEC), IBM, Intel, Microsoft, NEC and
Northern Telecom forms an association called USBIF (USB implementers Forum) and proposed
a solution, which allows a wide variety of peripheral devices to communicate with the computer
without compromising the performance.
USB provides easy attachment and removal of external devices such as printers,
scanners, modems, and cameras. USB is a replacement for the older serial port found and uses
the features of Plug-and-Play and Hot Swapping to achieve the easy attachment and removal.
Only one device can be attached to a standard serial port. Before USB, connecting devices to
your system was often a hassle. Modems and digital cameras were connected via the serial
port, which was quite slow, as only 1 bit is transmitted at a time through a serial port. In contrast,
up to 127 devices can, in theory, be attached to the USB network. When multiple USB devices
are to be attached to a computer, a device called a USB hub should be used. Consumers can
literally plug almost any USB device into their computer, and Windows will detect it and
automatically set-up the hardware settings for the device. Once that device has been installed
you can remove it from your system and the next time you plug it in, Windows will automatically
detect it. USB cables can carry any kind of data, including radio or television signals.
167
Embedded System
In USB communication PC acting as a host and the peripheral controlled by the host is
called device. The versions of USB are Low Speed (USB 1.0) of data transfer rate 1.5 Mbps
(Eg: Keyboards / Mice, Game Controllers, Virtual Reality Devices), Full Speed (USB 1.1) of
transfer rate 12 Mbps (Eg: Broadband Devices, Audio Devices, Microphones) and High Speed
(USB 2.0) of transfer rate up to 480 Mbps (Imaging Devices, Storage Devices). Currently, there
are four types of USB connectors: Type A, Type B, mini-A and mini-B and are supported by the
different USB specifications.
The electrical interface is based on a differential approach. The lines D+ and D- carry the
differential data. Since, the cable carries power and ground the peripheral devices can draw
power directly from the cable. The maximum length of the USB cable is restricted to 5 meters.
When an USB device is attached with the host, the host interrogates the connected device and
assigns an address and configuration value to it. This is called as enumeration. Finally, the host
system software loads an appropriate device driver and the peripheral is ready for use.
168
Embedded System
The transfers, which are supported by the USB convention, can be classified as control,
bulk, interrupt and isochronous transfers. Control Transfers are Burst, non-periodic types that
are host software-initiated request/response communication, typically used for command/status
operations. Isochronous Transfers are Periodic, continuous communication between host and
device, typically used for time-relevant information. This does not imply, however, that the
delivery need of such data is always time-critical. Interrupt Transfers are Small-data, low
frequency used in bounded-latency communication. Bulk Transfers: Non-periodic, large-packet
burst communication, typically used for data that can use any available bandwidth and can also
be delayed until bandwidth is available.
The USB packets can be broken down into token, data, handshake and start of frame. A
token packet includes four fields. A packet identifier (PID) determines the flow direction, OUT
(host to device) or IN (device to host). The 7-bit address field follows the identifier. Since, the
address 0 is reserved for the host, 127 devices only connected to the bus. The endpoint field
supports upto 16 endpoints for full speed devices and 2 for low speed devices. The last field
Cyclic Redundancy Check (CRC) field protects the packet from errors. Similarly the data packet
can carry 64 bytes for control, 1024 bytes for interrupt and isochronous and 512 bytes for bulk
transfers. Handshake packets report the status of the transaction. The start of frame packet is
generated by the host every one millisecond.
USB Devices have two forms of power classification: Self, Bus and Hybrid power. The
Self-powered device has it's own power supply and do not sink current from the USB cable. The
bus-powered device will take all their power from the USB bus. The USB device have to report
to the Host that it will be drawing an amount of electrical current from the Vbus in units of 100mA
load. A hybrid powered device takes power from both the USB bus as well as from it's own
power supply. Like in the case of a bus-powered device, it will have to report how many unit
load of electrical current it draws from the Host via the USB descriptors. USB carries data at the
rate of megabits per second, which is sufficient for "medium to low-speed peripherals". This
broad category includes telephones, digital cameras, modems, keyboards, mice, digital
joysticks, some CD-ROM drives, tape and floppy drives, digital scanners and specialty printers.
USBs data rate also accommodates a whole new generation of peripherals, including MPEG-2
video-base products, data gloves and digitizers. Computer-telephony integration is expected to
be a big growth area for PCs, and USB can provide an interface for Integrated Services Digital
Network (ISDN) and digital PBXs.
There are numerous applications, such as automotive and industrial systems, where the
designers must strike the balance between several conflicting requirements. First, fault
tolerance in a noisy environment is a must for the distributed embedded systems in motor
vehicles. Equally challenging is the demand for low cost and simple maintenance. Finally, the
availability of standard solutions for a large spectrum of applications is very desirable. The
169
Embedded System
protocol that meets these requirements is Controller Area Network (CAN). Robert Bosch
introduced the CAN serial bus in 1986, for automotive engine control communication.
The CAN bus is a two wire, half-duplex and high-speed serial bus. The CAN protocol
was internationally standardized in 1993 as ISO 11898-1 and comprises the data link layer of
the seven layer ISO/OSI reference model. The services such as error signaling, automatic re-
transmission of erroneous frames are user-transparent, which means the CAN chip
automatically performs these services. The CAN standard includes a physical layer and a data-
link layer, which defines a few different message types, arbitration rules for bus access and
methods for fault detection and fault confinement. The CAN standards are standard CAN 2.0A,
which uses 11-bit identifier and Extended CAN 2.0B, which uses 29-bit identifier. It is possible to
link upto 2032 devices in the network for CAN 2.0A and above 5 million devices in the network
for CAN 2.0B. The maximum speed of the CAN bus is 1 Mbps. The length is restricted to 40
meters for 1 Mbps rate.
The CAN bus is a broadcast type of bus. This means that all nodes can "hear" all
transmissions. There is no way to send a message to just a specific node; all nodes will
invariably pick up all traffic. The CAN hardware, however, provides local filtering so that each
node may react only on the interesting messages. The CAN network consists of Physical layer,
CAN controller and the software to implement the network. The physical layer includes the
cables, connectors and the transceivers. The CAN controller is classified into three types
depending on the Identifier. Part A controller uses 11-bit identifier, Part B passive uses both 11-
bit identifier, which also tolerate the 29-bit identifier but ignored and Part B controllers uses both
11-bit and 29-bit identifiers. CAN include a CSMA/CD (Carrier Sense Multiple Access with
Collision Detection). Each device can transmit a message and will retry if it loses the arbitration
to another device. Each device listens to the bus and thus a device trying to transmit can
determine easily if the message ongoing is the same than the one it tries to transmit. If it is
different, it releases the bus immediately. This arbitration mechanism insures that one master
always win, thus no messages will be lost to a collision. This mechanism is known as Arbitration
on message priority.
CAN uses short messages - the maximum utility load is 64 bits. There is no explicit
address in the messages; instead, the messages can be said to be contents-addressed, that is,
their contents implicitly determines their address. There are four different message types (or
"frames") on a CAN bus: the Data Frame, the Remote Frame, the Error Frame, and the
Overload Frame. The Data Frame is the most common message type. It comprises the
following major parts:
o For CAN 2.0A, an 11-bit Identifier and one bit, the RTR bit, which is dominant for
data frames.
o For CAN 2.0B, a 29-bit Identifier (which also contains two recessive bits: SRR
and IDE) and the RTR bit.
170
Embedded System
transmitter checks for the presence of the Acknowledge bit and retransmits the message
if no acknowledge was detected.
The Remote Frame is just like the Data Frame, with two important differences: it is
explicitly marked as a Remote Frame (the RTR bit in the Arbitration Field is recessive), and
there is no Data Field. The intended purpose of the Remote Frame is to solicit the transmission
of the corresponding Data Frame. If, say, node A transmits a Remote Frame with the Arbitration
Field set to 234, then node B, if properly initialized, might respond with a Data Frame with the
Arbitration Field also set to 234. There's one catch with the Remote Frame: the Data Length
Code must be set to the length of the expected response message. Otherwise the arbitration
will not work.
The Error Frame is a special message that violates the framing rules of a CAN message.
It is transmitted when a node detects a fault and will cause all other nodes to detect a fault - so
they will send Error Frames, too. The transmitter will then automatically try to retransmit the
message. There is an elaborate scheme of error counters that ensures that a node can't destroy
the bus traffic by repeatedly transmitting Error Frames. The Error Frame consists of an Error
Flag, which is 6 bits of the same value and an Error Delimiter, which is 8 recessive bits. The
Error Delimiter provides some space in which the other nodes on the bus can send their Error
Flags when they detect the first Error Flag. The Overload Frame is mentioned here just for
completeness. It is very similar to the Error Frame with regard to the format and it is transmitted
by a node that becomes too busy.
171
Embedded System
1 - Reserved
2 CAN_L CAN_L bus line (dominant low)
3 CAN_GND CAN Ground
4 - Reserved
5 (CAN_SHLD) Optional CAN shield
6 (GND) Optional CAN ground
7 CAN_H CAN_H bus line (dominant high)
8 - Reserved (error line)
9 CAN_V+ Optional power
Ethernet
In 1985, the Institute of Electrical and Electronic Engineers (IEEE) in the United States of
America, produced a series of standards for Local Area Networks (LANs) called the IEEE 802
standards. These have found widespread acceptability and now form the core of most LANs.
One of the IEEE 802 standards, IEEE 802.3, is a standard known as "Ethernet". This is the
most widely used LAN technology in the world today. Ethernet was developed by the Xerox
Corporation's Palo Alto Research Center (known colloquially as Xerox PARC) in 1972 and was
probably the first true LAN to be introduced. The IEEE standards have been adopted by the
International Standards Organization (ISO), and is standardized in a series of standards known
as ISO 8802-3. ISO was created in 1947 to construct world-wide standards for a wide variety of
engineering tasks. The name Ethernet comes from the physical concept of ether.
The ISO-OSI reference model specifies standards for describing "Open Systems
Interconnection" with the term 'open' chosen to emphasize the fact that by using these
international standards, a system may be defined which is open to all other systems obeying the
same standards throughout the world.
172
Embedded System
The communications engineer is concerned mainly with the protocols operating at the bottom
four layers (physical, data link, network, and transport) in the OSI reference model. These layers
173
Embedded System
provide the basic communications service. The layers above are primarily the concern of
computer scientists who wish to build distributed applications programs using the services
provided by the network. Ethernet uses a scheme known as carrier sense multiple access with
collision detection (CSMA/CD) governs the way the computers share the channel. When one
computer wants to send some information, it obeys the following algorithm:
Strictly, "Ethernet" refers to a product, which predates the IEEE 802.3 Standard. However
nowadays any 802.3 compliant network is referred to as an Ethernet. Over the years Ethernet
has continued to evolve, with 10Base5 using thick coaxial cable approved in 1986, 10Base2
using cheaper thin coaxial cable approved in 1986. Twisted pair wiring was used in 10BaseT,
approved in 1991 and fiber wire in 10BaseF, approved in 1994-95. In 1995 100Mbps Ethernet
was released, increasing the speed of Ethernet, which has since been further increased with the
release of Gigabit Ethernet in 1998-99. In the future, Ethernet will continue to increase in speed,
with 10 Gigabit Ethernet recently ratified, with 40 Gigabit arriving soon and 100 Gigabit Ethernet
technology demonstrations currently occurring. RJ-45 is a physical interface often used for
terminating twisted pair type cables. "RJ" stands for Registered Jack which is part of the United
States Code of Federal Regulations. It has eight "pins" or electrical connections per connector.
Pin
Wire Colour Function
No.
Transmit
1 WHITE/Orange
Data+
Transmit
2 ORANGE/White
Data-
Receive
3 WHITE/Green
Data+
4 BLUE/White None
5 WHITE/Blue None
Receive
6 GREEN/White
Data-
7 WHITE/Brown None
8 BROWN/White None
174
Embedded System
The protocols involved in Ethernet are IP, ICMP, MAC, TCP, UDP, FTP, SMTP, SNMP
and ARP. The Internetwork Protocol (IP) provides a best effort network layer service for
connecting computers to form a computer network. Each computer is identified by one or more
globally unique IP addresses. Each packet carries the IP address of the sending computer and
also the address of the intended recipient or recipients of the packet. Other management
information is also carried. The IP address is 32-bit numbers. The center for allocating IP
address is called Inter network information center (InterNIC). The IP addresses are divided into
5 classes class A, class B, class C, class D and class E.
The Medium Access Control (MAC) protocol is used to provide the data link layer of the
Ethernet LAN system. The Medium Access Control (MAC) transceiver contains the electronics
to interface a network interface card to an Ethernet cable. The unit contains a line driver (the
transmitter), a line receiver (the receiver), a carrier detect circuit (used to sense whether the
cable is in use) and control electronics to ensure correct operation of the device.
TCP (Transfer Control Protocol) is responsible for verifying the correct delivery of data
from client to server. Data can be lost in the intermediate network. TCP adds support to detect
errors or lost data and to trigger retransmission until the data is correctly and completely
received. UDP (User Datagram Protocol) is a communications protocol that offers a limited
amount of service when messages are exchanged between computers in a network that uses
the IP. UDP is an alternative to the TCP and, together with IP, is sometimes referred to as
UDP/IP. Like the Transmission Control Protocol, UDP uses the Internet Protocol to actually get
a data unit (called a datagram) from one computer to another. Unlike TCP, however, UDP does
not provide the service of dividing a message into packets (datagrams) and reassembling it at
the other end. FTP (File Transfer Protocol), SMTP (Simple Mail Transfer Protocol), HTTP
175
Embedded System
(Hyper Text Transfer Protocol) and SNMP (Simple Network Management Protocol) are the
application layer protocols that handles the details of particular application.Information is sent
around an Ethernet network in discreet messages known as frames. The frame structure is
quite simple, consisting of the following fields:
• The Preamble - This consists of seven bytes, all of the form "10101010". This allows the
receiver's clock to be synchronized with the sender's.
• The Start Frame Delimiter - This is a single byte ("10101011"), which is used to indicate
the start of a frame.
• The Destination Address - This is the address of the intended recipient of the frame. The
addresses in 802.3 use globally unique hardwired 48 bit addresses.
• The Source Address - This is the address of the source, in the same form as above.
• The Length - This is the length of the data in the Ethernet frame, which can be anything
from 0 to 1500 bytes.
• Data - This is the information being sent by the frame.
• Pad - 802.3 frame must be at least 64 bytes long, so if the data is shorter than 46 bytes, the
pad field must compensate. The reason for the minimum length lies with the collision
detection mechanism. In CSMA/CD the sender must wait at least two times the maximum
propagation delay before it knows that no collision has occurred. If a station sends a very
short message, then it might release the ether without knowing that the frame has been
corrupted.
• Checksum - This is used for error detection and recovery.
The above table describes the maximum distance of the Ethernet cable system for
different types of cables used in Ethernet system. The highest efficiency, reliability, high transfer
rate, number of devices in the network, and the large distance of communication of the Ethernet
network allows it to used in applications such as telecommunications, broadcasting, medical
applications and industrial networking applications.
176
Embedded System
23 WIRELESS NETWORKING
Unfortunately, these two resources are among the most severely limited in the
deployment of modern wireless networks: radio bandwidth because of the very tight situation
with regard to useful radio spectrum, and transmitter power because mobile and other portable
177
Embedded System
services require the use of battery power, which is limited. These two resources are simply not
growing or improving at rates that can support anticipated demands for wireless capacity. On
the other hand, one resource that is growing at a very rapid rate is that of processing power.
Moore’s Law, which asserts a doubling of processor capabilities every 18 months, has been
quite accurate over the past 20 years, and its accuracy promises to continue for years to come.
Given these circumstances, there has been considerable research effort in recent years aimed
at developing new wireless capacity through the deployment of greater intelligence in wireless
networks. A key aspect of this movement has been the development of novel signal
transmission techniques and advanced receiver signal processing methods that allow for
significant increases in wireless capacity without attendant increases in bandwidth or power
requirements. The purpose of this book is to present some of the most recent of these receiver
signal processing methods in a single place and in a unified framework.
GSM (Global System for Mobile communications) is the technology that underpins most
of the world's mobile phone networks. The GSM platform is a hugely successful wireless
technology and an unprecedented story of global achievement and cooperation. GSM has
become the world's fastest growing communications technology of all time and the leading
global mobile standard, spanning 210 countries. Today, GSM technology is in use by more than
one in five of the world's population – by mid-March 2006 there were over 1.7 billion GSM
178
Embedded System
subscribers, representing approximately 77% of the world's cellular market. The growth of GSM
continues unabated with almost 400 million new customers in the last 12 months. The progress
hasn't stopped there. Today's GSM platform is living, growing and evolving and already offers
an expanded and feature-rich 'family' of voice and multimedia services.
GSM is an open, digital cellular technology used for transmitting mobile voice and data
services. GSM differs from first generation wireless systems in that it uses digital technology
and time division multiple access transmission methods. GSM is a circuit-switched system that
divides each 200kHz channel into eight 25kHz time-slots. GSM operates in the 900MHz and
1.8GHz bands in Europe and the 1.9GHz PCS band in the US. GSM allowing the transmission
of basic data services such as SMS (Short Message Service). Another major benefit is its
international roaming capability, allowing users to access the same services when traveling
abroad as at home. This gives consumers seamless and same number connectivity in more
than 200 countries. GSM satellite roaming has also extended service access to areas where
terrestrial coverage is not available.
GSM Specifications
➢ Frequency – 900 MHz or 1800 MHz (Some countries in the Americas including Canada
and the United States use the 850 MHz and 1900 MHz bands, 400 and 450 MHz
frequency bands are assigned in some countries, notably Scandinavia)
179
Embedded System
➢ Channel separation - The separation between adjacent carrier frequencies. In GSM, this
is 200 kHz.
➢ Modulation - Gaussian minimum shift keying (GMSK).
➢ Transmission rate - 270 kbps. (A total of 156.25 bits is transmitted in 0.577 milliseconds,
giving a gross bit rate of 270.833 kbps)
➢ Access method - Time Division Multiple Access (TDMA) concept
➢ Speech coder - Linear predictive coding (LPC). Speech is encoded at 13 kbps.
Frequency Reuse
Frequency reuse is based on assigning to each cell a group of radio channels used
within a small geographic area. Cells are assigned a group of channels that is completely
different from neighboring cells. The coverage area of cells is called the footprint. This footprint
is limited by a boundary so that the same group of channels can be used in different cells that
are far enough away from each other so that their frequencies do not interfere. The number of
available frequencies is 7; the frequency reuse factor is 1/7.
TDMA Vs CDMA
In today’s world cell phone has become the single greatest tool in day today life. It has
become a necessity that business associates should be able to communicate on the go. An
important question when designing and standardizing cellular systems is the selection of the
multiple access schemes. There are three basic principles in multiple access, FDMA
(Frequency Division Multiple Access), TDMA (Time Division Multiple Access), and CDMA (Code
Division Multiple Access). All three principles allow multiple users to share the same physical
channel. But the two competing technologies differ in the way user sharing the common
resource. TDMA allows the users to share the same frequency channel by dividing the signal
into different time slots. Each user takes turn in a round robin fashion for transmitting and
receiving over the channel. CDMA uses a spread spectrum technology that is it spreads the
information contained in a particular signal of interest over a much greater bandwidth than the
original signal. In TDMA users can only transmit in their respective time slot. Unlike TDMA, in
CDMA several users can transmit over the channel at the same time. TDMA stands for "Time
Division Multiple Access", while CDMA stands for "Code Division Multiple Access". Three of the
180
Embedded System
four words in each acronym are identical, since each technology essentially achieves the same
goal, but by using different methods. Each strives to better utilize the radio spectrum by allowing
multiple users to share the same physical channel. More than one person can carry on a
conversation on the same frequency without causing interference. This is the magic of digital
technology.
Where the two competing technologies differ is in the manner in which users share the
common resource. TDMA does it by chopping up the channel into sequential time slices. Each
user of the channel takes turns transmitting and receiving in a round-robin fashion. In reality,
only one person is actually using the channel at any given moment, but he or she only uses it
for short bursts. He then gives up the channel momentarily to allow the other users to have their
turn. This is very similar to how a computer with just one processor can seem to run multiple
applications simultaneously.
Fig.23.3. TDMA
CDMA on the hand really does let everyone transmit at the same time. Conventional
wisdom would lead you to believe that this is simply not possible. Using conventional
modulation techniques, it most certainly is impossible. What makes CDMA work is a special
type of digital modulation called "Spread Spectrum". This form of modulation takes the user's
stream of bits and splatters them across a very wide channel in a pseudo-random fashion. The
"pseudo" part is very important here, since the receiver must be able to undo the randomization
in order to collect the bits together in a coherent order.
181
Embedded System
Fig.23.4. CDMA
182
Embedded System
Tags shapes: Label, Ticket, Card, Glass bead, Integrated, Wristband, Button
Tag Types: Active tag and passive tag/Read only tags, Write Once Read Many tags, Read
Write tags
183
Embedded System
RFID Standards
Quality is important for our clients. Elatec supports all ISO standards for RFID technology:
ISO 7816 is the standard for contact chip cards. ISO 7816-1 describes electrical and
mechanical issues; ISO 7816-2 describes size, order and functionality of contact areas of the
card and position of magstripe, if equipped with.
ISO 14443 is the standard for contactless proximity cards operating at 13.56 MHz in up to 5
inches distance.
ISO 15693 is the standard for contactless vicinity cards, i.e. cards which can be read from a
greater distance as compared to proximity cards. ISO 15693 systems operate on 13.56 MHz
frequency and offer maximum read distance of 1-1.5 metre or up to 50 inches.
ISO 18000-1: Generic parameters for air interface for global interface
ISO 18000-2: Parameters for air interface <135 kHz
ISO 18000-3: Parameters for air interface at 13.56 MHz
184
Embedded System
ISO 11784 describes the code structure and the information content of the codes stored in the
transponder: Identification code = 64 + 8 bits (including national code = 11 bits, country = 10
bits, data block = 1 bit, reserved = 14 bits, animal = 1 bit).
ISO 11785 describes the technical concept for the radio-frequency identification of animals, i.e.
the characteristics of the transmission protocols between transponder and transceiver.
ISO 11784 and ISO 11785 embody two fundamentally incompatible approaches: the so-called
fullduplex approach (FDX) and half-duplex approach (HDX), resulting in costly readers and
compromised performance for both the FDX and the HDX elements of the standard. HDX is
used exclusively in livestock applications, and has proven unsuitable for use in other
applications.
185
Embedded System
RFID System
186
Embedded System
RFID Advantages
Inventory control
Access control
Animal identification (from cows to birds)
Waste management
Laboratory analysis
Time and place data logging
Meat Processing
Vehicle identification
Ticketing
Fishery Management
Automatic Guided Vehicle positioning
Asset tracking
The use of RFID in tracking and access applications first appeared during the 1980s.
RFID quickly gained attention because of its ability to track moving objects. As the technology is
refined, more pervasive and possibly invasive uses for RFID tags are in the works. In a typical
RFID system, individual objects are equipped with a small, inexpensive tag. The tag contains a
transponder with a digital memory chip that is given a unique electronic product code. The
interrogator, an antenna packaged with a transceiver and decoder, emits a signal activating the
RFID tag so it can read and write data to it. When an RFID tag passes through the
electromagnetic zone, it detects the reader's activation signal. The reader decodes the data
encoded in the tag's integrated circuit (silicon chip) and the data is passed to the host computer.
The application software on the host processes the data, often employing Physical Markup
Language (PML).
Take the example of books in a library. Security gates can detect whether or not a book
has been properly checked out of the library. When users return items, the security bit is re-set
and the item record in the integrated library system is automatically updated. In some RFID
solutions a return receipt can be generated. At this point, materials can be roughly sorted into
bins by the return equipment. Inventory wands provide a finer detail of sorting. This tool can be
used to put books into shelf-ready order. RFID inlay imbedded within label material.
187
Embedded System
Bluetooth
Bluetooth is the name of a wireless technology standard for connecting devices, set to
replace cables. It uses radio frequencies in the 2.45 GHz range to transmit information over
short distances of generally 33 feet (10 meters) or less. By embedding a Bluetooth chip and
receiver into products, cables that would normally carry the signal can be eliminated. While
entertainment centers, computer systems, handheld PDAs, digital cameras and MP3 players,
continue to flourish, manufacturers and end-users alike are plagued by the growing complexity
of connecting devices. Proprietary cables, protocols and cradles simply complicate things as
companies seek a larger market share while buyers seek user-friendly gadgets that are
compatible with other products. Universal radio interface for ad-hoc wireless connectivity
Interconnecting computer and peripherals, handheld devices, PDAs, cell phones Replacement
of IrDA Short range (10 m), low power consumption, license-free 2.45 GHz ISM Voice and data
transmission, approx. 1 Mbit/s gross data rate
Bluetooth Features
188
Embedded System
Low Interference
Low Energy Consumption
Bluetooth radio hops faster and uses shorter packets
Spectrum spreading by frequency hopping in 79 hops displaced by 1 MHz, starting at
2.402GHz and finishing at 2.480GHz
23-hop system is used in few countries
The name "Bluetooth" is taken from the 10th century Danish King Harald Blatand – or
Harold Bluetooth in English. During the formative stage of the Trade Association a code name
was needed to name the effort. Over an evening discussing European history and the future of
wireless technology several felt it was appropriate to name the technology after King Blatand.
He had been instrumental in uniting warring factions in parts of what is now Norway, Sweden
and Denmark - just as the technology is designed to allow collaboration between differing
industries such as the computing, mobile phone and automotive markets. The code name stuck.
With embedded Bluetooth technology, all sorts of devices including cell phones,
headsets and earpieces, digital cameras and computers, can easily communicate with each
other without cables or setup. One wireless standard that is already familiar to many is IrDA or
infrared. Infrared uses pulses of non-visible light to communicate between two devices, such as
a remote control to a television or DVD player. One drawback of IrDA is that there must be a
clear line of sight between the two devices, and the other disadvantage is that IrDA normally
only operates between two devices at a time. An infrared remote control unit cannot
communicate with the DVD player while it is signaling the TV. Bluetooth overcomes these
limitations by using radio waves to send information in packet bursts. The bursts can be sent to
any device within 'earshot' allowing communication with several devices at once. With the
popularity of PDA-type products many have come to dread the bane of synchronizing with their
computer systems. Cradles, cables, and sometimes luck is needed to ensure a success.
Bluetooth technology eliminates this hassle, as the enabled devices easily recognize each other
and communicate spontaneously. Bluetooth devices in the house are always communicating
with one another as long as they are powered on. Each device sends out a signal, received by
the other devices that are sending out their own signals. The devices scan all signals to see if
any are addressing it. In this way, Bluetooth creates a personal-area network (PAN) in the home
and the user is not required to do anything special to get the devices to speak to one another.
They operate in a perpetual interactive mode by default. For example, let's assume you are
using your cell phone and headset while you copy a DVD from your entertainment center to
your desktop -- meanwhile your digital camera is offloading its contents to your laptop.
The Bluetooth devices that have business with one another will initiate their own
separate PAN (also called a piconet) and synchronize a random hopping scheme to create
interference-free communications. Known as spread-spectrum frequency hopping, the devices
will jump among 79 random frequencies within a specified range, changing about 1,600 times
per second in perfect unison. The likelihood that a device in another PAN will be using the same
frequency at the same time is minute. Hence several individual PANs or piconets can operate in
the house without interfering with one another. Each piconet can have 1 master and up to 7
slave devices. Future versions may allow linked piconets called scatternets. Though other
gadgets in the home might utilize the 2.45 GHz range, Bluetooth separates itself from these by
using a very weak signal that "flies under the radar." Conversely these other products rarely
cause interference with Bluetooth because frequency hopping keeps potential interference brief.
The maximum bandwidth for any single channel or frequency is 1 megabyte per second
(1Mbps), while individual packets range up to 2,745 bits. There are currently three flavors or
classifications of Bluetooth devices, relative to transmitting range. As the range is increased the
189
Embedded System
signal used in the respective classification is also stronger. Note that Class 3 devices are
comparatively rare.
ZigBee
The mission of the ZigBee Working Group is to bring about the existence of a broad
range of interoperable consumer devices by establishing open industry specifications for
unlicensed, control and entertainment devices requiring the lowest cost and lowest power
consumption communications between compliant devices anywhere in and around the home.
The ZigBee membership includes Philips, Honeywell and Invensys Metering Systems, and
others and is responsible for defining and maintaining higher layers above the MAC. The
alliance is also developing application profiles, certification programs, logos and a marketing
strategy. Philips Semiconductors and other chip vendors plan to launch their first ZigBee
products as early as 2003. ZigBee was formerly known as PURLnet, RF-Lite, Firefly, and
HomeRF Lite. The ZigBee specification is a combination of HomeRF Lite and the 802.15.4
specification. The spec operates in the 2.4GHz (ISM) radio band - the same band as 802.11b
standard, Bluetooth, microwaves and some other devices. It is capable of connecting 255
devices per network. The specification supports data transmission rates of up to 250 Kbps at a
range of up to 30 meters. ZigBee's technology is slower than 802.11b (11 Mbps) and Bluetooth
(1 Mbps) but it consumes significantly less power.
190
Embedded System
1998, many engineers realized that both WiFi and Bluetooth were going to be unsuitable
for many applications. In particular, need to design self-organizing ad-hoc networks of digital
radios. The simple one-chip design of Bluetooth digital radios was also inspirational. May 2003
the IEEE 802.15.4 standard completed. Summer 2003, Philips Semiconductors, a major
promoter, ceased its investment. Philips Lighting has, however, continued Philips' participation,
and Philips remains a promoter member on the ZigBee Alliance Board of Directors. October
2004 the ZigBee Alliance announced that its membership had more than doubled in the past
year and had grown to more than 100 member companies, in 22 countries. 14th December
2004 ZigBee specifications ratified. ZigBee is designed for wireless controls and sensors. It
could be built into just about anything you have around your home or office, including lights,
switches, doors and appliances. These devices can then interact without wires, and you can
control them all . . . from a remote control or even your mobile phone.
ZigBee operates in two main modes: non-beacon mode and beacon mode. Beacon mode is a
fully coordinated mode in that the entire device knows when to coordinate with one another. In
this mode, the network coordinator will periodically "wake-up" and send out a beacon to the
devices within its network. This beacon subsequently wakes up each device, who must
determine if it has any message to receive. If not, the device returns to sleep, as will the network
coordinator, once its job is complete. Non-beacon mode, on the other hand, is less coordinated,
as any device can communicate with the coordinator at will. However, this operation can cause
different devices within the network to interfere with one another, and the coordinator must
always be awake to listen for signals, thus requiring more power. In any case, ZigBee obtains its
overall low power consumption because the majority of network devices are able to remain
inactive over long periods of time.
191
Embedded System
switches, thermostats and furnaces, hotel-room air conditioners and the front desk, and central
command posts. It travels across greater distances and handles many sensors that can be
linked to perform different tasks. ZigBee works well because it aims low. Controls and sensors
don't need to send and receive much data. ZigBee has been designed to transmit slowly. It has
a data rate of 250kbps (kilobits per second), pitiful compared with Wi-Fi, which is hitting
throughput of 20Mbps or more. But because ZigBee transmits slowly, it doesn't need much
power, so batteries will last up to 10 years. Because ZigBee consumes very little power, a
sensor and transmitter that reports whether a door is open or closed, for example, can run for
up to five years on a single double-A battery. Also, operators are much happier about adding
ZigBee to their phones than faster technologies such as Wi-Fi; therefore, the phone will be able
to act as a remote control for all the ZigBee devices it encounters.
192
Embedded System
193
Embedded System
Appendix A:
194