You are on page 1of 195

Embedded System ARM Architecture & RTOS Programming

Vi Microsystems Pvt. Ltd., Chennai 96. 2


CONTENTS

1. Embedded Systems Introduction - 3
2. Microcontrollers - 8
3. ARM Architecture - 10
4. ARM7 Architecture - 18
5. LPC2148 Microcontroller - 25
6. Memory Organization - 40
7. Addressing Modes & Instruction Set - 45
8. Embedded C Programming - 52
9. Embedded IDE IAR Systems Embedded Workbench- 60
10. In System Programming ISP - 66
11. LPC2148 Design & Circuits - 69
12. Peripheral Interfacing Parallel Output Port - 76
13. Peripheral Interfacing Input Port - 91
14. Serial Port (UART) - 95
15. Timer - 106
16. Interrupts - 111
17. Analog To Digital Converter (ADC) - 122
18. Digital To Analog Converter (DAC) - 132
19. Sensor Interfacing - 135
20. VeePro - 138
21. RTOS Fundamentals - 152
22. Embedded Networking - 163
23. Wireless Networking - 178
Appendix - A - 195





Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 3


Introduction to Embedded System

An embedded system is a special-purpose computer system designed to perform one
or more dedicated functions. It is usually embedded as part of a complete device including
hardware and mechanical parts. Embedded systems control many of the common devices in
use today. Since the embedded system is dedicated to specific tasks, design engineers can
optimize it, reducing the size and cost of the product, or increasing the reliability and
performance.

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.


Difference Between Embedded System and PC

An embedded system has a self-contained operating system on a "chip" thus embedded
into the system and does not rely on having a hard disk with the operating system on it.
Because of that it will be much faster because the access time of the OS on a chip. Computers
share some elements with embedded systems such as the operating systems and
microprocessors, which power them but are not truly embedded systems, because they allow
different applications to be loaded and peripherals to be connected.


Embedded System Characteristics

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
EMBEDDED SYSTEMS
1
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 4
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:

Serial Communication Interfaces (SCI): RS-232, RS-422, RS-485 etc
Synchronous Serial Communication Interface: I
2
C, JTAG, SPI
Universal Serial Bus (USB)
Networks: Ethernet, Controller Area Network etc
Timers: PLL(s), Capture/Compare and Time Processing Units
Discrete IO: General Purpose Input/Output (GPIO)
Analog to Digital/Digital to Analog Converters (ADC/DAC)
The embedded CPU and the peripherals are the prime building blocks of the embedded
hardware.


Embedded Software

Embedded system designers use Compilers, Assemblers and Debuggers to develop
embedded system software. The principal role of embedded software is not the transformation
of data, but rather the interaction with the physical world. Software with a principal role of
interacting with the physical world must, of necessity, acquire some properties of the physical
world. Embedded software is usually written for special purpose hardware: that is computer
chips that are different from general purpose CPUs, sometimes using Real-time operating
system such as VxWorks, Embedded Linux, Cos, ThreadX, Windows CE, Nucleus etc.

For typical embedded programming designers use PC or Unix based cross-development
tools. These run on a development system, producing and debugging code that runs on a target
system. In addition to tools like those that would be used for PC development, there will almost
always be an assembler and there may be a simulator that will allow limited testing before the
target hardware is available. There are also assorted hardware tools available that can be a
great deal of help to the programmer who is familiar with their use. Many of the hardware tools
are expensive, but sometimes the impact on time-to-market is significant for embedded system
applications. Common hardware tools include emulators, usually connected to a software
debugger, and logic analyzers.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 5
Most embedded programming for large processors is done in compiled languages,
primarily C or C++ and most for small processors is done in assembly language.


Embedded software architectures

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.


Embedded System Development Cycle

























Fig. 1.1: Embedded Software Development Cycle

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 6
1. Writing Microcontroller Code

Software Code for a microcontroller is written in a programming language of choice
(Assembler or C). This source code is written with a standard ASCII text editor and saved as an
ASCII text file. Programming in assembler involves learning a microcontroller's specific
instruction set (assembler mnemonics), but results in the most compact and fastest code. A
higher-level language like C is for the most part independent of a microcontroller's specific
architecture, but still requires some controller specific extensions of the standard language to be
able to control all of a chip's peripherals and functionality. The penalty for more portable code
and faster program development is a larger code size (20%...40% compared to assembler).

2. Translating the Code

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, Compilers, Linkers and Librarians

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.

3. Debugging the Code

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).

Integrated Development Environment: An Integrated Development Environment puts all of
the previously discussed software components under one common unified user interface, so
that it becomes possible to make a code change and get the modified code loaded into the
emulator with a few mouse clicks, instead of dozens.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 7
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.

4. OTP and Flash Programming

Out-of-Circuit Programming: OTP microcontrollers are typically programmed out-of-circuit.
That means the microcontroller is programmed before being soldered on the target board. For
that purpose production grade programmers offer a choice of optional, high quality, expensive,
zero-insertion-force (ZIF) pin adapters to support different package flavors.

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.













Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 8



A programmable device used in majority of embedded applications is
microcontroller. By the mid-1980s, the most of the processors 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

Microcontrollers are classified based on the manufacturer, number of bits that to be
processing, Processor architecture and memory architecture. Microcontrollers are available in 4-
bit, 8-bit, 16-bit and 32-bit processing package. Depends upon the processor architecture
microcontrollers are subdivided into CISC (Complex Instruction Set Computer) and RISC
(Reduced Instruction Set Computer). Von-Neumann Architecture and Harvard architecture are
the memory architecture variants of the microcontroller. Some of the microcontroller
manufactures are Altera, Analog Devices, Atmel, Cypress MicroSystems, Dallas
Semiconductor, Freescale Semiconductor, Fujitsu, Infineon, Intel, Lattice Semiconductor,
Microchip Technology, National Semiconductor, NEC, Philips Semiconductors, Rabbit
Semiconductor, Renesas Technology, Silabs, STMicroelectronics, Texas Instruments, Toshiba,
Xilinx, ZiLOGetc.,

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.

Complex Instruction Set Computer (CISC): Complex Instruction Set Computer
Architecture is the traditional architecture of a computer, which uses microcode to execute very
comprehensive instructions. Instructions may be variable in length and use all addressing
modes, requiring complex circuitry to decode them. A complex instruction set computer is a
microprocessor instruction set architecture (ISA) in which each instruction can execute several
low-level operations, such as a load from memory, an arithmetic operation, and a memory store,
all in a single instruction. Examples of CISC processors are the MCS-51 (8051 derivatives),
System/360, VAX, PDP-11, Motorola 68000 family, and Intel x86 architecture based processors.
MICROCONTROLLERS
2
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 9
















Fig. 2.1: RISC Vs CISC

Reduced Instruction Set Computer: Reduced Instruction Set Computer is a computer
architecture that reduces chip complexity by using simpler instructions. RISC compilers have to
generate software routines to perform complex instructions that were previously done in
hardware by CISC computers. In RISC, the microcode layer and associated overhead is
eliminated. RISC keeps instruction size constant, bans the indirect addressing mode and retains
only those instructions that can be overlapped and made to execute in one machine cycle or
less. The RISC chip is faster than its CISC counterpart and is designed and built more
economically. The reduced instruction set computer is a CPU design philosophy that favors an
instruction set reduced both in size and complexity of addressing modes, in order to enable
easier implementation, greater instruction level parallelism, and more efficient compilers.
Common RISC microprocessors families include the DEC Alpha, ARC, ARM, AVR, MIPS, PA-
RISC, PIC, PowerPC, etc.


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

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 10


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.



















Fig. 3.1: 32-bit Microcontroller Market


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:

Very fast responses to non-deterministic events
Simpler assembler coding
High throughput
Low power consumption

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)

ARM ARCHITECTURE
3
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 11
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 cores are simple compared to most other general-purpose processors.
A typical ARM chip contains several peripheral controllers, a DSP and some amount of
on-chip memory.
ARM ISA and pipeline designs are aimed to minimizing energy consumption.
ARM architecture is highly modular: the only mandatory component of an ARM
processor is the integer pipeline. All other components, including caches, MMU, FP unit
and other co-processors are optional.
ARM architecture provides a high performance for embedded applications.


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:
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 12
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,
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 13
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.

ARM becomes the Advanced RISC Machine:

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-
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 14
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.


ARM Processor Families

Revision Core Implementation ISA Enhancements
ARM v1 (1985) ARM1
The first commercial RISC
26-bit addressing
ARM v2 (1987) ARM2
32-bit multiplier & coprocessor support
On-chip cache;
ARM v2a ARM3 Atomic swap instruction, 32-bit addressing;
ARM v3 (1992) ARM6; ARM7DI
Separate CPSR and SPSR; Additional modes:
undefined instruction and abort;
MMU support, virtual memory
ARM v3M ARM7M Signed and unsigned long multiply instructions
ARM v4 (1996) Strong ARM
Load-store instructions for signed and unsigned
half-words/bytes; 26-bit addressing mode no
longer supported
ARM v4T
ARM7TDMI;
ARM9T
Thumb
ARM v5TE (1999) ARM9E; ARM10E
Superset of the ARM v4T; Extra instructions for
changing state between ARM and Thumb;
Enhanced multiply instructions; Extra DSP-type
instructions; Faster multiply accumulate
ARM v5TEJ ARM7EJ; ARM926EJ Java acceleration
ARM v6 (2001)
ARM11

Improved multiprocessor instructions; Unaligned
and mixed endian data handling; New
multimedia instructions; SIMD instructions;
Trust-Zone for creation a trusted computer base
within a system-on-chip
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 15
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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 16
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.

DSP extensions: ARM-based systems typically perform signal-processing tasks using
dedicated DSP coprocessors. Some DSP support is provided by the main ARM core. A
corresponding ISA extension was introduced in fifth version of the architecture. It features
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 17
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 Family Attributes


ARM7 ARM9 ARM10 ARM11

Pipeline depth
Frequency (MHz)
mW/MHZ
MIPS/MHz
Architecture
Multiplier


3-stage
80
0.06
0.97
Von Neumann
832

5-stage
150
0.19
1.1
Harvard
832

6-stage
260
0.5
1.3
Harvard
1632

8-stage
335
0.4
1.2
Harvard
1632



ARM Manufacturers















NXP
LPC211x, LPC212X,
LPC219X, LPC22XX,
LPC23XX, LPC24XX
Atmel
AT76C110,
AT91SC321RC,
AT91SAM
Analog
Devices
AD20MSP430, AD6522,
AD6526, AD6528
Intel
D5205, D5313, IXP220,
IXP225, IXP1200

ARM7 ARCHITECTURE
4
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 18



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).

C ARM7TDMI - Integer processor
C ARM7TDMI-S - Synthesizable version of the ARM7TDMI processor
C ARM7EJ-S - Synthesizable core with DSP and Jazelle technology enhancements for
Java acceleration
C ARM720T - Cached core with Memory Management Unit (MMU) supporting operating
systems including Windows CE, Palm OS, Symbian OS and Linux

The ARM7 variants are described below.


Cache
Size
Memory
Contr.
Bus
Interface
Thumb DSP Jazalle
ARM720T
8K
(unified)
MMU AHB YES NO NO
ARM7EJ-S YES YES YES YES
ARM7TDMI YES YES NO NO
ARM7TDMI -S YES YES NO NO

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.

+ Generic layout can be ported to specific process technologies
+ Unified memory bus simplifies SoC integration process
+ ARM and Thumb instructions sets can be mixed with minimal overhead to support
application requirements for speed and code density
+ Code written for ARM7TDMI-S is binary-compatible with other members of the ARM7 Family
and forwards compatible with ARM9, ARM9E and ARM10 families, thus it's quite easy to
port your design to higher-level microcontroller or microprocessor
+ Static design and lower power consumption are essential for battery -powered devices
+ Instruction set can be extended for specific requirements using coprocessors
+ EmbeddedICE-RT and optional ETM units enable extensive, real-time debug facilities

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 19
ARM7TDMI Main Features

* 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).
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 20


























Fig. 4.1: ARM Registers


Processor Modes
















Fig. 4.2: ARM Processor Modes
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 21
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.

Each of the unbanked registers R0 to R7 are used as 32-bit general-purpose registers in
all processor modes. The hidden from a program at different times registers are called banked
registers. The hidden registers are available only when the processor is in a particular mode (for
example Abort mode has banked registers R13-abt, R14-abt and SPSR-abt). The banked
registers R8 to R14 are used dependently of the current processor mode. Almost all instructions
allow the banked registers to be used wherever a general-purpose register is allowed. All
processor modes except System mode have a set of associated banked registers that are
subset of the main 16 registers. Register R13 is used as a stack pointer (SP) in ARM assembly
language (the C and C++ compilers always use R13 as the stack pointer).

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 (PC8) for ARM, or (PC4) for Thumb.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 22
The Current Program Status Register (CPSR)
The CPSR is used in user-level programs to store the condition code bits.
The bit 0 to bit 4 at the bottom of the register controls the processor mode.
T The bit 5 indicates the processor mode
T=1: 16-bit Thumb Mode
T=0: 32-bit ARM Mode
F Interrupt enable bit for FIQ. FIQ is enabled with F=0.
I Interrupt enable bit for IRQ. IRQ is enabled with I=0.
N (Negative) - Set for a negative result.
Z (Zero) - Set for a zero result.
C (Carry) - Set for a carry-out event.
V (oVerflow) - Set for an overflow event.





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.














The Load-Store Architecture

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
Fig 4.3: ARM CPSR format
Fig 4.4: ARM operation modes
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 23
such memory-to-memory operations. All ARM instructions fall into one of the following 3
categories.

Data processing instructions: Arithmetic & logical operations of data in registers.
Data transfer instructions:
= Load: memory register;
= Store: memory register;
= Swap.
Control flow:
= Conditional / unconditional branch;
= Branch / branch with link / branch with exchange.


The I/O System

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 ARMs
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.


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 24
Pipelining

Pipelining, a standard feature in RISC processors, is much like an assembly line.
Because the processor works on different steps of the instruction at the same time, more
instructions can be executed in a shorter period of time.
A useful method of demonstrating this is the laundry analogy. Let's say that there are
four loads of dirty laundry that need to be washed, dried, and folded. We could put the first load
in the washer for 30 minutes, dry it for 40 minutes, and then take 20 minutes to fold the clothes.
Then pick up the second load and wash, dry, and fold, and repeat for the third and fourth loads.
Supposing we started at 6 PM and worked as efficiently as possible, we would still be doing
laundry until midnight. However, a smarter approach to the problem would be to put the second
load of dirty laundry into the washer after the first was already clean and whirling happily in the
dryer. Then, while the first load was being folded, the second load would dry, and a third load
could be added to the pipeline of laundry. Using this method, the laundry would be finished by
9:30.
A RISC processor pipeline operates in much the same way, although the stages in the
pipeline are different. Different processors have different numbers of steps. The original 3-stage
ARM pipeline that remained essentially unchanged from the first ARM processor to the
ARM7TDMI core. It is a classical fetch-decode-execute pipeline, which completes one
instruction per cycle. Instruction cycle consists of the operations such as

1. Instruction fetched from memory
2. Decoding of registers used in instruction
3. Register(s) read from register bank, Shift and ALU operation, Write register(s) back to
register bank

Since PC is accessible as a general-purpose register, there are several places in the
pipeline where the next instruction address can be issued. Under normal conditions, it is
incremented on every cycle during the fetch stage. If a data processing instruction specifies R15
as its destination operand, then the result of the ALU operation is used as the next instruction
address (a load to R15 has a similar effect).














3-Stage
Pipelining
Fig. 4.5: 3-stage pipelining
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 25


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 I
2
C-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.













Fig. 5.1: LPC2148 in a tiny LQFP package
LPC2148 MICROCONTROLLER
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 I
2
C-bus (400 Kbit/s), SPI and SSP
Fig. 5.2: LPC2148 Block Diagram
5
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 26

































Pin Description:

Symbol Pin Description
P0.21/PWM5/
AD1.6/CAP1.3

1
P0.21 General-purpose input/output digital pin (GPIO)
PWM5 Pulse Width Modulator output 5
AD1.6 ADC 1, input 6
CAP1.3 Capture input for Timer 1, channel 3
P0.22/AD1.7/
CAP0.0/MAT0. 0
2
P0.22 General-purpose input/output digital pin (GPIO)
AD1.7 ADC 1, input 7
CAP0.0 Capture input for Timer 0, channel 0
MAT0.0 Match output for Timer 0, channel 0
3 Input to the RTC oscillator circuit
Fig. 5.3: LPC2148 IC Pin Layout
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 27
RTXC1

P1.19/
TRACEPKT3

4

P1.19 General-purpose input/output digital pin (GPIO)
TRACEPKT3 Trace Packet, bit 3. Standard I/O port with
internal pull-up


RTXC2

5

Output from the RTC oscillator circuit


VSS

6

Ground: 0 V reference

VDDA

7

Analog 3.3 V power supply: This should be nominally the
same voltage as VDD but should be isolated to minimize
noise and error. This voltage is only used to power the on-
chip ADC(s) and DAC

P1.18/
TRACEPKT2

8

P1.18 General-purpose input/output digital pin (GPIO).
TRACEPKT2 Trace Packet, bit 2. Standard I/O port with
internal pull-up.

P0.25/AD0.4/
AOUT

9

P0.25 Genera-purpose input/output digital pin (GPIO)
AD0.4 ADC 0, input 4
AOUT DAC output

D+ 10 SB bi-directional D+ line
D- 11 USB bi-directional D- line
P1.17/
TRACEPKT1

12

P1.17 General-purpose input/output digital pin (GPIO)
TRACEPKT1 Trace Packet, bit 1. Standard I/O port with
internal pull-up

P0.28/AD0.1/
CAP0.2/MAT0.2

13
P0.28 General-purpose input/output digital pin (GPIO)
AD0.1 ADC 0, input 1
CAP0.2 Capture input for Timer 0, channel 2
MAT0.2 Match output for Timer 0, channel 2
P0.29/AD0.2/
CAP0.3/MAT0.3

14

P0.29 Genera-purpose input/output digital pin (GPIO)
AD0.2 ADC 0, input 2
CAP0.3 Capture input for Timer 0, Channel 3
MAT0.3 Match output for Timer 0, channel 3

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 28
P0.30/AD0.3/
EINT3/CAP0.0

15

P0.30 General-purpose input/output digital pin (GPIO)
AD0.3 ADC 0, input 3
EINT3 External interrupt 3 input
CAP0.0 Capture input for Timer 0, channel 0

P1.16/
TRACEPKT0

16
P1.16 General-purpose input/output digital pin (GPIO)
TRACEPKT0 Trace Packet, bit 0. Standard I/O port with
internal pull-up
P0.31/UP_LED/
CONNECT

17

P0.31 General-purpose output only digital pin (GPO)
UP_LED USB GoodLink LED indicator. It is LOW when
device is configured (non-control endpoints enabled). It is
HIGH when the device is not configured or during global
suspend
CONNECT Signal used to switch an external 1.5 k
SoftConnect USB feature. Important: This is a digital output
only pin. This pin MUST NOT be externally pulled LOW
when RESET pin is LOW or the JTAG port will be disabled.


VSS

18

Ground: 0 V reference.

P0.0/TXD0/
PWM1

19

P0.0 General-purpose input/output digital pin (GPIO)
TXD0 Transmitter output for UART0
PWM1 Pulse Width Modulator output 1

P1.31/TRST

20

P1.31 General-purpose input/output digital pin (GPIO)
TRST Test Reset for JTAG interface

P0.1/RXD0/
PWM3/EINT0

21

P0.1 General-purpose input/output digital pin (GPIO)
RXD0 Receiver input for UART0
PWM3 Pulse Width Modulator output 3
EINT0 External interrupt 0 input

P0.2/SCL0/
CAP0.0
22

P0.2 General-purpose input/output digital pin (GPIO)
SCL0 I2C0 clock input/output. Open-drain output (for I
2
C-
bus compliance)
CAP0.0 Capture input for Timer 0, channel 0


VDD

23
3.3 V power supply: This is the power supply voltage for the
core and I/O ports.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 29
P1.26/RTCK

24

P1.26 General-purpose input/output digital pin (GPIO)
RTCK Returned Test Clock output. Extra signal added to
the JTAG port Assists debugger synchronization when
processor frequency varies. Bi-directional pin with internal
pull-up
Note: LOW on RTCK while RESET is LOW enables pins
P1.31:26 to operate as Debug port after reset.


VSS

25

Ground: 0 V reference.

P0.3/SDA0/
MAT0.0/EINT1

26

P0.3 General-purpose input/output digital pin (GPIO)
SDA0 I
2
C0 data input/output. Open-drain output (for I
2
C-
bus compliance)
MAT0.0 Match output for Timer 0, channel 0
EINT1 External interrupt 1 input

P0.4/SCK0/
CAP0.1/AD0.6

27

P0.4 General-purpose input/output digital pin (GPIO)
SCK0 Serial clock for SPI0. SPI clock output from master
or input to slave
CAP0.1 Capture input for Timer 0, channel 0
AD0.6 ADC 0, input 6

P1.25/EXTIN0

28

P1.25 General-purpose input/output digital pin (GPIO)
EXTIN0 External Trigger Input. Standard I/O with internal
pull-up



P0.5/MISO0/
MAT0.1/AD0.7


29

P0.5 General-purpose input/output digital pin (GPIO)
MISO0 Master In Slave OUT for SPI0. Data input to SPI
master or data output from SPI slave
MAT0.1 Match output for Timer 0, channel 1
AD0.7 ADC 0, input 7
P0.6/MOSI0/
CAP0.2/AD1.0

30

P0.6 General-purpose input/output digital pin (GPIO)
MOSI0 Master Out Slave In for SPI0. Data output from
SPI master or data input to SPI slave
CAP0.2 Capture input for Timer 0, channel 2
AD1.0 ADC 1, input 0
P0.7/SSEL0/
PWM2/EINT2

31

P0.7 General-purpose input/output digital pin (GPIO)
SSEL0 Slave Select for SPI0. Selects the SPI interface
as a slave
PWM2 Pulse Width Modulator output 2
EINT2 External interrupt 2 input

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 30

P1.24/
TRACECLK

32

P1.24 General-purpose input/output digital pin (GPIO)
TRACECLK Trace Clock. Standard I/O port with internal
pull-up


P0.8/TXD1/
PWM4/AD1.1

33

P0.8 General-purpose input/output digital pin (GPIO)
TXD1 Transmitter output for UART1
PWM4 Pulse Width Modulator output 4
AD1.1 ADC 1, input 1


P0.9/RXD1/
PWM6/EINT3

34

P0.9 General-purpose input/output digital pin (GPIO)
RXD1 Receiver input for UART1
PWM6 Pulse Width Modulator output 6
EINT3 External interrupt 3 input


P0.10/RTS1/
CAP1.0/AD1.2

35

P0.10 General purpose input/output digital pin (GPIO)
RTS1 Request to Send output for UART1
CAP1.0 Capture input for Timer 1, channel 0
AD1.2 ADC 1, input 2


P1.23/
PIPESTAT2

36

P1.23 General-purpose input/output digital pin (GPIO)
PIPESTAT2 Pipeline Status, bit 2. Standard I/O port with
internal pull-up


P0.11/CTS1/
CAP1.1/SCL1

37

P0.11 General-purpose input/output digital pin (GPIO)
CTS1 Clear to Send input for UART1
CAP1.1 Capture input for Timer 1, channel 1
SCL1 I
2
C1 clock input/output. Open-drain output (for I
2
C-
bus compliance)


P0.12/DSR1/
MAT1.0/AD1.3

38
P0.12 General-purpose input/output digital pin (GPIO)
DSR1 Data Set Ready input for UART1.
MAT1.0 Match output for Timer 1, channel 0.
AD1.3 ADC input 3

P0.13/DTR1/
MAT1.1/AD1.4
39
P0.13 General-purpose input/output digital pin (GPIO)
DTR1 Data Terminal Ready output for UART1
MAT1.1 Match output for Timer 1, channel 1.
AD1.4 ADC input 4
P1.22/
PIPESTAT1
40
P1.22 General-purpose input/output digital pin (GPIO)
PIPESTAT1 Pipeline Status, bit 1. Standard I/O port with
internal pull-up
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 31

P0.14/DCD1/
EINT1/SDA1

41

P0.14 General-purpose input/output digital pin (GPIO)
DCD1 Data Carrier Detect input for UART1
EINT1 External interrupt 1 input.
SDA1 I
2
C1 data input/output. Open-drain output (for
I
2
C-bus compliance) Note: LOW on this pin while RESET
is LOW forces on-chip boot loader to take over control of
the part after reset


VSS

42

Ground: 0 V reference


VDD

43

3.3 V power supply: This is the power supply voltage for
the core and I/O ports


P1.21/
PIPESTAT0

44

P1.21 General-purpose input/output digital pin (GPIO)
PIPESTAT0 Pipeline Status, bit 0. Standard I/O port
with internal pull-up


P0.15/RI1/
EINT2/AD1.5

45

P0.15 General-purpose input/output digital pin (GPIO)
RI1 Ring Indicator input for UART1
EINT2 External interrupt 2 input.
AD1.5 ADC 1, input 5

P0.16/EINT0/
MAT0.2/CAP0.
2

46

P0.16 General-purpose input/output digital pin (GPIO)
EINT0 External interrupt 0 input
MAT0.2 Match output for Timer 0, channel 2
CAP0.2 Capture input for Timer 0, channel 2


P0.17/CAP1.2/
SCK1/MAT1.2

47

P0.17 General-purpose input/output digital pin (GPIO)
CAP1.2 Capture input for Timer 1, channel 2
SCK1 Serial Clock for SSP. Clock output from master
or input to slave
MAT1.2 Match output for Timer 1, channel 2

P1.20/
TRACESYNC

48

P1.20 General-purpose input/output digital pin (GPIO)
TRACESYNC Trace Synchronization. Standard I/O port
with internal pull-up.
Note: LOW on this pin while RESET is LOW enables pins
P1.25:16 to operate as Trace port after reset.

VBAT

49

RTC power supply voltage: 3.3 V on this pin supplies the
power to the RTC

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 32

VSS

50

Ground: 0 V reference


VDD

51

3.3 V power supply: This is the power supply voltage for the core
and I/O ports


P1.30/TMS

52

P1.30 General-purpose input/output digital pin (GPIO)
TMS Test Mode Select for JTAG interface


P0.18/CAP1.3/
MISO1/MAT1.3

53

P0.18 General-purpose input/output digital pin (GPIO)
CAP1.3 Capture input for Timer 1, channel 3.
MISO1 Master In Slave Out for SSP. Data input to SPI
master or data output from SSP slave.
MAT1.3 Match output for Timer 1, channel 3.


P0.19/MAT1.2/
MOSI1/CAP1.2

54

P0.19 General-purpose input/output digital pin (GPIO).
MAT1.2 Match output for Timer 1, channel 2.
MOSI1 Master Out Slave In for SSP. Data output from SSP
master or data input to SSP slave.
CAP1.2 Capture input for Timer 1, channel 2.


P0.20/MAT1.3/
SSEL1/EINT3

55
P0.20 General-purpose input/output digital pin (GPIO)
MAT1.3 Match output for Timer 1, channel 3
SSEL1 Slave Select for SSP. Selects the SSP interface as a
slave
EINT3 External interrupt 3 input


P1.29/TCK

56

P1.29 General-purpose input/output digital pin (GPIO)
TCK Test Clock for JTAG interface



RESET
57

External reset input: A LOW on this pin resets the device,
causing I/O ports and peripherals to take on their default states,
and processor execution to begin at address 0. TTL with
hysteresis, 5 V tolerant.


P0.23/VBUS

58

P0.23 General-purpose input/output digital pin (GPIO)
VBUS Indicates the presence of USB bus power
Note: This signal must be HIGH for USB reset to occur


VSSA

59
Analog ground: 0 V reference. This should nominally be the
same voltage as VSS, but should be isolated to minimize noise
and error

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 33

P1.28/TDI

60

P1.28 General-purpose input/output digital pin (GPIO)
TDI Test Data in for JTAG interface


XTAL2

61

Output from the oscillator amplifier


XTAL1

62

Input to the oscillator circuit and internal clock generator circuits


VREF

63

ADC reference voltage: This should be nominally less than or
equal to the VDD voltage but should be isolated to minimize
noise and error. Level on this pin is used as a reference for
ADC(s) and DAC.


P1.27/TDO

64

P1.27 General-purpose input/output digital pin (GPIO).
TDO Test Data out for JTAG interface.



LPC2148 Architecture

The ARM7TDMI-S is a general-purpose 32-bit microprocessor, which offers high
performance and very low power consumption. The ARM architecture is based on Reduced
Instruction Set Computer (RISC) principles, and the instruction set and related decode
mechanism are much simpler than those of micro programmed Complex Instruction Set
Computers (CISC). This simplicity results in a high instruction throughput and impressive real-
time interrupt response from a small and cost-effective processor core. Pipeline techniques are
employed so that all parts of the processing and memory systems an operate continuously.
Typically, while one instruction is being executed, its successor is being decoded, and a third
instruction is being fetched from memory.

The ARM7TDMI-S processor also employs a unique architectural strategy known as
Thumb, which makes it ideally suited to high-volume applications with memory restrictions, or
applications where code density is an issue. The key idea behind Thumb is that of a super-
reduced instruction set. Essentially, the ARM7TDMI-S processor has two instruction sets:

The standard 32-bit ARM set.
A 16-bit Thumb set.

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 users code
on 500 kB. The LPC2148 flash memory provides a minimum of 100000 erase/write cycles and
20 years of data-retention.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 34
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.





































Fig. 5.4: LPC2148 Block Diagram
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 35
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.

General purpose timers/external event counters: The Timer/Counter is designed to count
cycles of the peripheral clock (PCLK) or an externally supplied clock and 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. Multiple pins can be selected to perform a single capture or
match function, providing an application with or and and, as well as broadcast functions
among them. The LPC2148 can count external events on one of the capture inputs if the
minimum external pulse is equal or longer than a period of the PCLK. In this configuration,
unused capture lines can be selected as regular timer capture inputs, or used as external
interrupts.
+ A 32-bit timer/counter with a programmable 32-bit prescaler
+ External event counter or timer operation
+ Four 32-bit capture channels per timer/counter that can take a snapshot of the timer
value when an input signal transitions. A capture event may also optionally generate an
interrupt.
+ Four 32-bit match registers that allow:
Continuous operation with optional interrupt generation on match.
Stop timer on match with optional interrupt generation.
Reset timer on match with optional interrupt generation.
+ Four external outputs per timer/counter corresponding to match registers, with the
following capabilities:
Set LOW on match.
Set HIGH on match.
Toggle on match.
Do nothing on match.

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).

+ 16 B Receive and Transmit FIFOs
+ Register locations conform to 16C550 industry standard
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 36
+ Receiver FIFO trigger points at 1 B, 4 B, 8 B, and 14 B
+ Built-in fractional baud rate generator covering wide range of baud rates without a need
for external crystals of particular values
+ Transmission FIFO control enables implementation of software (XON/XOFF) flow control
on both UARTs
+ LPC2148 UART1 equipped with standard modem interface signals. This module also
provides full support for hardware flow control (auto-CTS/RTS)

I
2
C-bus serial I/O controller: The LPC2148 contains two I
2
C-bus controllers. The I
2
C-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
2
C-bus
is a multi-master bus; it can be controlled by more than one bus master connected to it. The I
2
C-
bus implemented in LPC2148 supports bit rates up to 400 kbit/s (Fast I
2
C-bus).

+ Compliant with standard I
2
C-bus interface
+ Easy to configure as master, slave, or master/slave
+ Programmable clocks allow versatile rate control
+ Bi-directional data transfer between masters and slaves
+ Multi-master bus (no central master)
+ Arbitration between simultaneously transmitting masters without corruption of serial data
on the bus
+ Serial clock synchronization allows devices with different bit rates to communicate via
one serial bus
+ Serial clock synchronization can be used as a handshake mechanism to suspend and
resume serial transfer
+ The I
2
C-bus can be used for test and diagnostic purposes

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.

+ Compliant with SPI specification.
+ Synchronous, Serial, Full Duplex, Communication.
+ Combined SPI master and slave.
+ Maximum data bit rate of one eighth of the input clock rate.

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 Motorolas SPI, TIs 4-wire SSI and National Semiconductors Micro-
wire buses.
+ Synchronous serial communication
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 37
+ Master or slave operation
+ 8-frame FIFOs for both transmit and receive
+ Four bits to 16 bits per frame

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 successive approximation analog to digital converter
+ Measurement range of 0 V to VREF (2.0 V s VREF s VDDA)
+ Each converter capable of performing more than 400000 10-bit samples per second
+ Every analog input has a dedicated result register to reduce interrupt overhead
+ Burst conversion mode for single or multiple inputs
+ Optional conversion on transition on input pin or timer match signal
+ Global Start command for both converters

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.

+ Fully compliant with USB 2.0 Full-speed specification
+ Supports 32 physical (16 logical) endpoints
+ Supports control, bulk, interrupt and isochronous endpoints
+ Scalable realization of endpoints at run time
+ Endpoint maximum packet size selection by software at run time
+ RAM message buffer size based on endpoint realization and maximum packet size
+ Supports bus-powered capability with low suspend current
+ Supports DMA transfer on all non-control endpoints
+ One duplex DMA channel serves all endpoints
+ Allows dynamic switching between CPU controlled and DMA modes

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 38
generate a system reset if the user program fails to feed (or reload) the watchdog within a
predetermined amount of time.

+ Internally resets chip if not periodically reloaded
+ Debug mode
+ Enabled by software but requires a hardware reset or a watchdog reset/interrupt to be
disabled
+ Incorrect/Incomplete feed sequence causes reset/interrupt if enabled
+ Flag to indicate watchdog reset
+ Programmable 32-bit timer with internal prescaler
+ Selectable time period from (T
cy(PCLK)
256 4) to (T
cy(PCLK)
232 4) in multiples of
T
cy(PCLK)
4.

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).

+ Measures the passage of time to maintain a calendar and clock.
+ Ultra-low power design to support battery powered systems.
+ Provides Seconds, Minutes, Hours, Day of Month, Month, Year, Day of Week, and Day
of Year.
+ Can use either the RTC dedicated 32 kHz oscillator input or clock derived from the
external crystal/oscillator input at XTAL1. Programmable reference clock divider allows
fine adjustment of the RTC.
+ Dedicated power supply pin can be connected to a battery or the main 3.3 V.

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 f
osc
and the ARM processor clock
frequency is referred to as CCLK for purposes of rate equations, etc. f
osc

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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 39
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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 40



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
MEMORY ORGANIZATION
6
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 41
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

Data Bus



Fig. 6.1: Von-Neumann Architecture

Harvard Architecture: The term Harvard architecture originally referred to computer
architectures that uses physically separate storage devices for their instructions and data.
Harvard architecture has separate data and instruction busses, allowing transfers to be
performed simultaneously on both busses.








Fig. 6.2: Harvard Architecture

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.


The Memory System

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.


CPU
MEMORY
PROGRAM &
DATA
DATA
MEMORY
PROGRAM
MEMORY


CPU
Data Bus
Address Bus Address Bus
Data Bus
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 42
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.

















LPC2148 Memory Organization

























Fig. 6.4: LPC2148 Memory Map
Fig. 6.3: ARM memory organization
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 43
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.

VPB Peripheral Base Address Peripheral Name
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14 22

23
24
25
26
27
28 35

36
37 126

127
0xE000 0000
0xE000 4000
0xE000 8000
0xE000 C000
0xE001 0000
0xE001 4000
0xE001 8000
0xE001 C000
0xE002 0000
0xE002 4000
0xE002 8000
0xE002 C000
0xE003 0000
0xE003 4000
0xE003 8000
0xE005 8000
0xE005 C000
0xE006 0000
0xE006 4000
0xE006 8000
0xE006 C000
0xE007 0000
0xE008 C000
0xE009 0000
0xE009 4000
0xE01F 8000
0xE01F C000
Watchdog timer
Timer 0
Timer 1
UART0
UART1
PWM
Not used
I
2
C0
SPI0
RTC
GPIO
Pin connect block
Not used
ADC0
Not used

I
2
C1
ADC1
Not used
SSP
DAC
Not used

USB
Not used

System Control Block
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 44
On-chip Flash memory Organization

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) Organization

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.




Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 45
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

The five addressing modes are used by processor are

Mode 1 -Shifter operands for data processing instructions
Mode 2 - Load and store word or unsigned byte
Mode 3 - Load and store half-word or load signed byte
Mode 4 - Load and store multiple
Mode 5 - Load and store coprocessor

In ARM state, all instructions are conditionally executed according to the state of the
CPSR condition codes and the instructions 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 instructions 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.

Code Suffix Flags Meaning

ADDRESSING MODES AND INSTRUCTION SET
7
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 46
0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
EQ
NE
CS
CC
MI
PL
VS
VC
HI
LS
GE
LT
GT
LE
AL
Z set
Z clear
C set
C clear
N set
N clear
V set
V clear
C set and Z clear
C clear or Z set
N equals V
N not equal to V
Z clear and (N equals V)
Z set or (N not equal to V)
(ignored)
Equal
Not equal
Unsigned higher or same
Unsigned lower
Negative
Positive or Zero
Overflow
No overflow
Unsigned higher
Unsigned lower or same
Greater or equal
Less than
Greater than
Less than or equal
always


Instruction Set Summary

Mnemonic Description
Flags
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>}
<target_address>
Branch, Branch and
Link
None
BIC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Bit Clear N, Z
BX {<cond>} <Rm>
Branch and
Exchange
None
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>{!},
<registers>
Load Multiple None
LDR {<cond>} <Rd>, <addressing_mode> Load Register None
LDRB {<cond>} <Rd>, <addressing_mode> Load Register Byte None
LDRH {<cond>} <Rd>, <addressing_mode>
Load Register
Halfword
None
LDRSB {<cond>} <Rd>, <addressing_mode> Load Register None
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 47
Signed Byte
LDRSH {<cond>} <Rd>, <addressing_mode>
Load Register
Signed Halfword
None
MLA {<cond>}{S} <Rd >, <Rm>, <Rs>, <Rn> Accumulate
N, Z (C is
unpredictable)
MOV {<cond>}{S} <Rd>, <shifter_operand> Move N, Z, C
MRS {<cond>} <Rd >, CPSR
MRS {<cond>} <Rd >, SPSR
Move PSR into
eneral-Purpose
Register
None
MSR {<cond>} CPSR_<fields>, #<immediate>
MSR {<cond>} CPSR_<fields>, <Rm>
MSR {<cond>} SPSR_<fields>, #<immediate>
MSR {<cond>} SPSR_<fields>, <Rm>
Move to Status
Register from ARM
Register

N/A

MUL {<cond>}{S} <Rd >, <Rm>, <Rs> Multiply
N, Z (C is
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
RSC {<cond>}{S} <Rd>, <Rn>, <shifter_operand>
Reverse Subtract
with Carry
N, Z, V, C
SBC {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Subtract with Carry N, Z, V, C
SMLAL{<cond>}{S} <Rd_LSW>, <Rd_MSW>, <Rm>,
<Rs>
Signed Multiply-
Accumulate Long
N, Z (V, C are
unpredict)
SMULL{<cond>}{S} <Rd_LSW>, <Rd_MSW>, <Rm>,
<Rs>

Signed Multiply Long
N, Z (V, C are
unpredict)

STM {<cond>}<addressing_mode>, <Rn>{!},
<registers>
Store Multiple None
STR {<cond>} <Rd>, <addressing_mode> Store Register None
STRB {<cond>} <Rd>, <addressing_mode> Store Register Byte None
STRH {<cond>} <Rd>, <addressing_mode> Store Register
Halfword
None

SUB {<cond>}{S} <Rd>, <Rn>, <shifter_operand> Subtract N, Z, V, C
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 48
SWI {<cond>} <immediate_24> Software Interrupt N/A
SWP {<cond>} <Rd>, <Rm>, [<Rn>] Swap None
SWP {<cond>} B <Rd>, <Rm>, [<Rn>] Swap Byte None
TEQ {<cond>} <Rn>, <shifter_operand> Test Equivalence N, Z, C
TST {<cond>} <Rn>, <shifter_operand> Test N, Z, C
UMLAL {<cond>}{S} <Rd_LSW>, <Rd_MSW>,
<Rm>, <Rs>
Unsigned Multiply-
Accumulate Long
N, Z (V, C are
unpredict)
UMULL- {<cond>}{S} <Rd_LSW>, <Rd_MSW>,
<Rm>, <Rs>
Unsigned Multiply
Long
N, Z (V, C are
unpredict)



Assembly Programming Examples

1. Addition Write a program to add two 32-bit numbers

#include <iolpc2148.h>
main
LDR R0,=0x0FF57341
LDR R1,=0xBF230EA1
ADD R3,R0,R1
NOP
END


2. Subtraction Write a program to subtract 4FFFFFEB h from 07A21111h

#include <iolpc2148.h>
main
LDR R0,=0x4FFFFFEB
LDR R1,=0x07A21111
SUB R3,R0,R1
NOP
END

3. Multiplication Write a program to multiply 12345h and 12h

#include <iolpc2148.h>
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 49
main
LDR R0,=0x00012345
LDR R1,=0x00000012
MUL R3,R0,R1
NOP
END


4. Write a program to divide AA19h by 15Eh

#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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 50
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

7. Write a program to AND two 32-bit numbers FFFFFFFFh and 0000FFFFh

#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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 51
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.

























EMBEDDED C PROGRAMMING
8
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 52
C is a general-purpose language. It is closely associated with the UNIX operating
system for which it was developed. In 1972 Dennis Ritchie at Bell Labs writes C and in 1978 the
publication of the C Programming Language by Kernighan & Ritchie caused a revolution in the
computing world. In 1983, the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The resulting definition, the
ANSI standard, or "ANSI C", was completed late 1988. The latest version of Microsoft C is now
considered to be the most powerful and efficient C compiler for personal computers. C stands
for Common. Embedded C is not part of the C language as such. Rather, it is a C language
extension that is the subject of a technical report by the ISO working group named "Extensions
for the Programming Language C to Support Embedded Processors". The hardware I/O
extension is a portability feature of Embedded C. Its goal is to allow easy porting of device-
driver code between systems.
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.


The layout of C Programs

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 ;
}
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 53
Base data types

The compiler uses the following sizes for the various C data types:

char and unsigned char 1 byte
short int and unsigned short int 2 bytes
int and unsigned int 4 bytes
long and unsigned long 4 bytes
long long and unsigned long long 8 bytes
float 4 bytes (32 bits)
double 8 bytes (64 bits)
long double 8 bytes (64 bits)
enum up to 4 bytes
bit fields up to 32 bits


Embedded C Operators

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 54
- 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

iolpc2148.h The standard iolpc2148.h library is provided for LPC2148 processor
declarations


Keywords

Reserved keywords specified by the standard C are given in the following table.










Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 55
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.


C Programming Examples

1. Write a program to add two 8-bit numbers

#include<iolpc2148.h>

int a,b,c;

void main()
{
a=0x62;
b=0x6C;
c=a+b;
printf("\n\rvalue of c is:%x",c);
}


2. Write a program to find the Factorial of the given number

#include<iolpc2148.h>
#include<stdio.h>

int factorial(long x);
long fact=2;

void main()
{
while(1)
{
printf("\n\rfactorial of given number is:%d",factorial(fact));
fact++;
}
}
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 56

int factorial(long x)
{
long c,f;
f=x;
c=f*(--x);
while(x!=1)
{
c=c*(--x);
}
return(c);
}

3. Write a program to find the largest value in the given array

#include<iolpc2148.h>
#include<stdio.h>

int array[10]={23,12,45,67,89,9,97,107,46,78};

int finding_max(int *p);

void main()
{
printf("\n\r maximum value is:%d",finding_max(array));
}

int finding_max(int *p)
{
int i,max;
max=array[0];
for(i=1;i<10;i++)
{
if(max>p[i])
max=max;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 57
else
max=p[i];
}
return(max);
}


4. Write a program to find the Prime number

#include<iolpc2148.h>
#include<stdio.h>

int finding_next_prime(int x);
int current_prime=2;

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;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 58
}
else
a=a++;
}
return(x);
}


5. Write a program to sorting the array in Ascending Order

#include<iolpc2148.h>
#include<stdio.h>

int array[10]={9,8,7,6,5,4,3,2,1,0};
int sorted[10];

void sorting(int *p);
void display(int *p);

void main()
{
sorting(array);
display(array);
}

void sorting(int *p)
{
int i,j,buffer;

for(i=0;i<10;i++)
for(j=i+1;j<10;j++)
{
if(p[j]<p[i])
{
buffer=p[i];
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 59
p[i]=p[j];
p[j]=buffer;
}
}
}

void display(int *p)
{
int i;
for(i=0;i<10;i++)
printf("\n\rsort is:%d",p[i]);
}


Exercises:

1. Write a program to find the Armstrong number from 0 to 500
(Ex: 153 = (1*1*1)+(5*5*5)+(3*3*3)
2. Convert centigrade into Fahrenheit Scales
3. Write a program to perform logical operations like AND, OR, XOR and NOT
4. Write a program to find whether the entered string is your name or not
5. Write a program to find the number of small letters, capital letters, special characters and
numbers in an array.
6. Write a program to sort the array in descending order
7. Write a program to convert the Hexadecimal value into decimal
8. Write a program to move the data 55h to the memory locations from 00000050h to
00000500h
9. Write a program to generate a divisors of a integer
10. Write a program to check whether a given number is perfect or not (Hint: A positive integer n
is called a perfect number if it is equal to the sum of all of its positive divisors, excluding n
itself. Ex: 1,2,3 are the divisors of 6, the sum of 1,23 is 6. So 6 is the perfect number)



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 60



In computing, an integrated development environment (IDE) is a software application
that provides comprehensive facilities to computer programmers for software development. An
IDE normally consists of a source code editor, a compiler and/or interpreter, build automation
tools, and (usually) a debugger. IAR Systems Embedded Workbench is a fully featured
Integrated Development Environment (IDE) that provides seamless integration and easy access
to all the development tools developed by IAR Systems. IAR Embedded Workbench is a set of
development tools for building and debugging embedded applications using assembler, C and
C++. It provides a completely integrated development environment including a project manager,
editor, build tools and debugger. IAR Embedded Workbench for ARM provides extensive
support for a wide range of ARM devices, hardware debug systems and RTOSs, and generates
very compact and efficient code.

Key features

+ Fully integrated development environment for building and debugging embedded
applications
+ ARM EABI 2.0 (Embedded Application Binary Interface) compatible with other AEABI
compliant tools
+ Advanced optimization technology generating the most compact and efficient code
+ Automatic checking of MISRA C rules for safety-critical systems
+ Support for ARM, Thumb1 and Thumb-2 processor modes and VFP co-processors
+ ETM Trace support via IAR J-Trace
+ Extensive supports for various debug systems, such as simulator, JTAG/SWD, ROM-
monitor and ETM Trace
+ RTOS-aware debugging with built-in or 3rd-party plug-ins
+ Ready-made peripheral register definition files for devices from Analog Devices, Atmel,
Cirrus Logic, Freescale, Handshake Solutions, Intel, Luminary, Marvell, NetSilicon, OKI,
Philips, Samsung, Sharp, STmicroelectronics and Texas Instruments
+ Flash loaders and over 1000 project examples included for most popular devices and
evaluation boards
+ Tight integration with
- IAR PowerPac (RTOS and middleware tools)
- IAR J-Link and IAR J-Trace (hardware debug probes)
- IAR visualSTATE (state machine design and verification tools)

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.

EMBEDDED IDE IAR SYSTEMS EMBEDDED WORKBENCH
9
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 61
The IAR Embedded Workbench IDE is a flexible integrated development environment,
allowing you to develop applications for a variety of different target processors. It provides a
convenient Windows interface for rapid development and debugging.


Steps for creating application code using IAR Systems

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 levelsproject, 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.
Creating The New Project
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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 62
The project will appear in the Workspace window.











A project filewith the filename extension ewpwill 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 FileNew 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 filewith the filename extension ewwhas now been created in the projects
directory. This file lists all projects that you will add to the workspace.

Adding Files to Project

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


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 63
project. Otherwise click the right mouse button on the project in the workspace window and
choose AddAdd filename.c.























Setting Project Options

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.




















The Target options
page in the General Options
category is displayed. In the
general options window the
settings must be
Target Core:
ARM7TDMIS
Output:
Executable
Library Configuration:
Normal
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 64
Click OK to set the options you have specified. The project is now ready to be built.
Linking the Application
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.


To compile the file filename.c, select it in the Workspace window. Choose
Project>Compile. Alternatively, click the Compile button in the toolbar or choose the Compile
command from the context menu that appears when you right-click on the selected file in the
Workspace window. The progress will be displayed in the Build messages window. The
executable file in the HEX format will be created in the chosen directory. The HEX file will be
downloaded to the target system by using ISP (In System Programmer).
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.


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 65















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.




Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 66



The In-system programming (ISP) is performed without removing the microcontroller
from the system. The in-system programming facility consists of a series of internal hardware
resources coupled with internal firmware to facilitate remote programming of the LPC2148
through the serial port (RS232). This firmware is provided by Philips (NXP). For in-system
programming facility Launch LPC214x_ISP, a software utility is available from Philips.


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.

Before downloading do the following
1. Reset the device
2. Keep the pin P0.14 in logical 0 which will forces on-chip boot loader
3. Connect the RS232 cable with the UART 0 lines
4. Connect Power Supply with required rating
























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.

IN SYSTEM PROGRAMMING (ISP)
10
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 67























Click Upload to Flash, the previous contents in the memory is erased and the file is
loaded in the Flash memory.



























Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 68
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.

There are many benefits to incorporating In-System Programming (ISP) in the
development and production stages of Embedded System Applications In-system programming
is a valuable feature that allows system firmware to be upgraded without disassembling the
embedded system to physically replace memory. Most microcontrollers can be reprogrammed
from a PC or laptop via an inexpensive RS-232 serial interface and a few logic gates. When
launched, the in-system programming feature auto bauds to the detected baud rate and begins
execution of a command-driven, ROM-based bootstrap loader. Embedded designs with in-
system programmability allow generic products to be software-customized right before
shipment. The feature also reduces life cycle cost by permitting existing applications to be
upgraded without disassembling the application. Secure microcontrollers can use this feature to
load the customer's proprietary software into the application where it will be automatically
encrypted and protected against unauthorized access.



































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 69










































Circuits








LPC2148 DESIGN & CIRCUITS
11
LPC2148
Microcontroller
UART 0
UART 1
CAN
Connector
USB
Connector
Power On/Off Switch
Power Supply
Connector
Reset
Switch
Regulator
RS-232
Driver
12 MHz Crystal
Oscillator
LCD
TFT LCD
Connector
Program/
Execution
Mode Switch
Expansion
Header
32.748 kHz
Crystal for
RTC
LEDs
Switch
ADC
Input

P1
CASIO SOCKET
VCC
GND
SW1
POWER ON/OFF SW
1
1
2
2
3
3
VCC

L1
LED
R1
330E
VCC
(POWER ON LED)
L1
LED
R1
330E
VCC
(POWER ON LED)
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 70




















































C16
22PF
Y1
32.748KHz
3
U5
LPC 2148
P0.21/PWM5/AD1.6/CAP1.3
1
P0.22/AD1.7/CAP0.0/MAT0.0
2
RTXC1
3
P1.19/TRACEPKT3
4
RTXC2
5
VSS
6
VDDA
7
P1.18/TRACEPKT2
8
P0.25/AD0.4/AOUT
9
D+
10
D-
11
P1.17/TRACEPKT1
12
P0.28/AD0.1/CAP0.2/MAT0.2
13
P0.29/AD0.2/CAP0.3/MAT0.3
14
P0.30/AD0.3/EINT3/CAP0.0
15
P1.16/TRACEPKT0
16
P0.31/UP_LED/CONNECT
17
VSS
18
P0.0/TXD0/PWM1
19
P1.31/TRST-
20
P0.1/RXD0/PWM3/EINT0
21
P0.2/SCL0/CAP0.0
22
VDD
23
P1.26/RTCK
24
VSS
25
P0.3/SDA0/MAT0.0/EINT1
26
P0.4/SCK0/CAP0.1/AD0.6
27
P1.25/EXTIN0
28
P0.5/MISO0/MAT0.1/AD0.7
29
P0.6/MOSI0/CAP0.2/AD1.0
30
P0.7/SSEL0/PWM2/EINT2
31
P1.24/TRACECLK
32
P0.8/TXD1/PWM4/AD1.1
33
P0.9/RXD1/PWM6/EINT3
34
P0.10/RTS1/CAP1.0/AD1.2
35
P1.23/PIPESTAT2
36
P0.11/CTS1/CAP1.1/SCL1
37
P0.12/DSR1/MAT1.0/AD1.3
38
P0.13/DTR1/MAT1.1/AD1.4
39
P1.22/PIPESTAT1
40
P0.14/DCD1/EINT1/SDA1
41
VSS
42
VDD
43
P1.21/PIPESTAT0
44
P0.15/RI1/EINT2/AD1.5
45
P0.16/EINT0/MAT0.2/CAP0.2
46
P0.17/CAP1.2/SCK1/MAT1.2
47
P1.20/TRACESYNC
48
VBAT
49
VSS
50
VDD
51
P0.20/MAT1.3/SSEL1/EINT3
55
P1.30/TMS
52
P0.19/MAT1.2/MOSI1/CAP1.2
54
P0.18/CAP1.3/MISO1/MAT1.3
53
P1.29/TCK
56
RESET-
57
P0.23/VBUS
58
VSSA
59
P1.28/TDI
60
XTAL2
61
XTAL1
62
VREF
63
P1.27/TD0
64
C15
22PF
+3.3V
+3.3V
RXD0
TXD0
RESET-
MCLK
XTALIN
P0.2
VBUS
SW0
RXD1
TXD1
SSEL0
MOSI0
MISO0
SCK0
LCD2
LCD1
LCD0
P0.15
P0.14
LED1
LED0
SW1
LCD7
LCD6
LCD5
LCD4
LCD3
P0.25
P0.22
P0.21
P0.20
RX0BF
TX1RTS
TX0RTS
INT
CONNECT
SSEL1
P0.29
ADC
D-
D+
RS
DIOW
P0.3
P1.27
P1.28
P1.29
LCD_EN
P1.30
P1.31
C16
22PF
Y1
32.748KHz
3
U5
LPC 2148
P0.21/PWM5/AD1.6/CAP1.3
1
P0.22/AD1.7/CAP0.0/MAT0.0
2
RTXC1
3
P1.19/TRACEPKT3
4
RTXC2
5
VSS
6
VDDA
7
P1.18/TRACEPKT2
8
P0.25/AD0.4/AOUT
9
D+
10
D-
11
P1.17/TRACEPKT1
12
P0.28/AD0.1/CAP0.2/MAT0.2
13
P0.29/AD0.2/CAP0.3/MAT0.3
14
P0.30/AD0.3/EINT3/CAP0.0
15
P1.16/TRACEPKT0
16
P0.31/UP_LED/CONNECT
17
VSS
18
P0.0/TXD0/PWM1
19
P1.31/TRST-
20
P0.1/RXD0/PWM3/EINT0
21
P0.2/SCL0/CAP0.0
22
VDD
23
P1.26/RTCK
24
VSS
25
P0.3/SDA0/MAT0.0/EINT1
26
P0.4/SCK0/CAP0.1/AD0.6
27
P1.25/EXTIN0
28
P0.5/MISO0/MAT0.1/AD0.7
29
P0.6/MOSI0/CAP0.2/AD1.0
30
P0.7/SSEL0/PWM2/EINT2
31
P1.24/TRACECLK
32
P0.8/TXD1/PWM4/AD1.1
33
P0.9/RXD1/PWM6/EINT3
34
P0.10/RTS1/CAP1.0/AD1.2
C16
22PF
Y1
32.748KHz
3
U5
LPC 2148
P0.21/PWM5/AD1.6/CAP1.3
1
P0.22/AD1.7/CAP0.0/MAT0.0
2
RTXC1
3
P1.19/TRACEPKT3
4
RTXC2
5
VSS
6
VDDA
7
P1.18/TRACEPKT2
8
P0.25/AD0.4/AOUT
9
D+
10
D-
11
P1.17/TRACEPKT1
12
P0.28/AD0.1/CAP0.2/MAT0.2
13
P0.29/AD0.2/CAP0.3/MAT0.3
14
P0.30/AD0.3/EINT3/CAP0.0
15
P1.16/TRACEPKT0
16
P0.31/UP_LED/CONNECT
17
VSS
18
P0.0/TXD0/PWM1
19
P1.31/TRST-
20
P0.1/RXD0/PWM3/EINT0
21
P0.2/SCL0/CAP0.0
22
VDD
23
P1.26/RTCK
24
VSS
25
P0.3/SDA0/MAT0.0/EINT1
26
P0.4/SCK0/CAP0.1/AD0.6
27
P1.25/EXTIN0
28
P0.5/MISO0/MAT0.1/AD0.7
29
P0.6/MOSI0/CAP0.2/AD1.0
30
P0.7/SSEL0/PWM2/EINT2
31
P1.24/TRACECLK
32
P0.8/TXD1/PWM4/AD1.1
33
P0.9/RXD1/PWM6/EINT3
34
P0.10/RTS1/CAP1.0/AD1.2
35
P1.23/PIPESTAT2
36
P0.11/CTS1/CAP1.1/SCL1
37
P0.12/DSR1/MAT1.0/AD1.3
38
P0.13/DTR1/MAT1.1/AD1.4
39
P1.22/PIPESTAT1
40
P0.14/DCD1/EINT1/SDA1
41
VSS
42
VDD
43
P1.21/PIPESTAT0
44
P0.15/RI1/EINT2/AD1.5
45
P0.16/EINT0/MAT0.2/CAP0.2
46
P0.17/CAP1.2/SCK1/MAT1.2
47
P1.20/TRACESYNC
48
VBAT
49
VSS
50
VDD
51
P0.20/MAT1.3/SSEL1/EINT3
55
P1.30/TMS
52
P0.19/MAT1.2/MOSI1/CAP1.2
54
P0.18/CAP1.3/MISO1/MAT1.3
53
P1.29/TCK
56
RESET-
57
P0.23/VBUS
58
VSSA
59
P1.28/TDI
60
XTAL2
61
XTAL1
62
VREF
63
P1.27/TD0
64
C15
22PF
+3.3V
+3.3V
RXD0
TXD0
RESET-
MCLK
XTALIN
P0.2
VBUS
SW0
RXD1
TXD1
SSEL0
MOSI0
MISO0
SCK0
LCD2
LCD1
35
P1.23/PIPESTAT2
36
P0.11/CTS1/CAP1.1/SCL1
37
P0.12/DSR1/MAT1.0/AD1.3
38
P0.13/DTR1/MAT1.1/AD1.4
39
P1.22/PIPESTAT1
40
P0.14/DCD1/EINT1/SDA1
41
VSS
42
VDD
43
P1.21/PIPESTAT0
44
P0.15/RI1/EINT2/AD1.5
45
P0.16/EINT0/MAT0.2/CAP0.2
46
P0.17/CAP1.2/SCK1/MAT1.2
47
P1.20/TRACESYNC
48
VBAT
49
VSS
50
VDD
51
P0.20/MAT1.3/SSEL1/EINT3
55
P1.30/TMS
52
P0.19/MAT1.2/MOSI1/CAP1.2
54
P0.18/CAP1.3/MISO1/MAT1.3
53
P1.29/TCK
56
RESET-
57
P0.23/VBUS
58
VSSA
59
P1.28/TDI
60
XTAL2
61
XTAL1
62
VREF
63
P1.27/TD0
64
C15
22PF
+3.3V
+3.3V
RXD0
TXD0
RESET-
MCLK
XTALIN
P0.2
VBUS
SW0
RXD1
TXD1
SSEL0
MOSI0
MISO0
SCK0
LCD2
LCD1
LCD0
P0.15
P0.14
LED1
LED0
SW1
LCD7
LCD6
LCD5
LCD4
LCD3
P0.25
P0.22
P0.21
P0.20
RX0BF
TX1RTS
TX0RTS
INT
CONNECT
SSEL1
P0.29
ADC
D-
D+
RS
DIOW
P0.3
P1.27
P1.28
P1.29
LCD_EN
P1.30
P1.31

C3
0.1uF
C2
0.1uF
+3.3V

R31
1K
+3.3V
P0.2
R29
1K
P0.3
+3.3V
R26
SW1
+3.3V
R31
1K
+3.3V
P0.2
R29
1K
P0.3
+3.3V
R26
SW1
+3.3V

R17
1K
+3.3V
DIOW
RS
+3.3V
R18
1K
R17
1K
+3.3V
DIOW
RS
+3.3V
R18
1K
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 71




















































LCD0
LCD4
LCD3
LCD2
LCD1
LCD7
LCD6
LCD5
LCD1
N_LCD DISPLAY
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
R19
1K
TP2
10K
VCC
VCC
VCC
VCC
RS
RESET-
BR
BR
LCD_EN
DIOW

SW5
TINNY SW
1
1
2
2
3
3
SW4
MICRO SW
1 2
U1
MCP1319MT - 45
RST
1
VSS
2
RST
3
MR
4
VDD
5
R38 1K
X1
12Mhz
NC
3
GND
4
OUT
5
VCC
6
R41
100K
+3.3V
+3.3V
VCC
+3.3V
RSTSW-
P0.14
XTALIN
RESET-
RSTSW- RESET

SW0
C17
18pF
SW3
M
I
C
R
O

S
W
R32
1K
+3.3V
R33
100E
SW0
C17
18pF
SW3
M
I
C
R
O

S
W
R32
1K
+3.3V
R33
100E
C17
18pF
SW3
M
I
C
R
O

S
W
R32
1K
+3.3V
R33
100E

SW1
C18
18pF
SW2
M
I
C
R
O

S
W
+3.3V
R35
100E
R34
1K
SW1
C18
18pF
SW2
M
I
C
R
O

S
W
+3.3V
R35
100E
R34
1K
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 72




















































C9
0.1uF
P2
9 PIN 'D' MALE CON.
5
9
4
8
3
7
2
6
1
C7
0.1uF
C13
0.1uF
L3
LED
U4
ICL232
C1+
1
C1-
3
C2+
4
C2-
5
T1IN
11
R1OUT
12
T2IN
10
R2OUT
9
VCC
16
V+
2
V-
6
GND
15
T1OUT
14
R1IN
13
T2OUT
7
R2IN
8
R8
1.5K
C8
0.1uF
L2
LED
+3.3V
+3.3V
TXD0
RX0_IN
TX0_OUT
RXD0
TX0_OUT
RX0_IN
TX0_OUT
RX0_IN
P4
3 PIN RMC
1
2
3
TX1_OUT
RX1_IN
RXD1
TXD1
RX1_IN
TX1_OUT
C9
0.1uF
P2
9 PIN 'D' MALE CON.
5
9
4
8
3
7
2
6
1
C7
0.1uF
C13
0.1uF
L3
LED
U4
ICL232
C1+
1
C1-
3
C2+
4
C2-
5
T1IN
11
R1OUT
12
T2IN
10
R2OUT
9
VCC
16
V+
2
V-
6
GND
15
T1OUT
14
R1IN
13
T2OUT
7
R2IN
8
R8
1.5K
C8
0.1uF
L2
LED
+3.3V
+3.3V
TXD0
RX0_IN
TX0_OUT
C9
0.1uF
P2
9 PIN 'D' MALE CON.
5
9
4
8
3
7
2
6
1
C7
0.1uF
C13
0.1uF
L3
LED
U4
ICL232
C1+
1
C1-
3
C2+
4
C2-
5
T1IN
11
R1OUT
12
T2IN
10
R2OUT
9
VCC
16
V+
2
V-
6
GND
15
T1OUT
14
R1IN
13
T2OUT
7
R2IN
8
R8
1.5K
C8
0.1uF
L2
LED
+3.3V
+3.3V
TXD0
RX0_IN
TX0_OUT
RXD0
TX0_OUT
RX0_IN
TX0_OUT
RX0_IN
P4
3 PIN RMC
1
2
3
TX1_OUT
RX1_IN
RXD1
TXD1
RX1_IN
TX1_OUT

P0.29
SSEL0
P0.2
P0.25
P1.30
SSEL1
P0.3
P1.29 CONNECT
P5
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
P0.22 P1.27
VBUS P1.28
P1.31
P0.21 P0.15
P0.20
VCC
+3.3V
TXD0
RXD0
SW1
LED0
P7
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
RXD1
SW0
LED1
TXD1
VCC
+3.3V
LCD3
LCD2
LCD1
LCD0
LCD7
LCD6
LCD5
LCD4
RS
P0.29
SSEL0
P0.2
P0.25
P1.30
SSEL1
P0.3
P1.29 CONNECT
P5
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
P0.22 P1.27
VBUS P1.28
P1.31
P0.21 P0.15
P0.20
VCC
+3.3V
TXD0
P0.29
SSEL0
P0.2
P0.25
P1.30
SSEL1
P0.3
P1.29 CONNECT
P5
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
P0.22 P1.27
VBUS P1.28
P1.31
P0.21 P0.15
P0.20
VCC
+3.3V
TXD0
RXD0
SW1
LED0
P7
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
RXD1
SW0
LED1
TXD1
VCC
+3.3V
LCD3
LCD2
LCD1
LCD0
LCD7
LCD6
LCD5
LCD4
RS

C_SSEL0
TX1RTS
TX0RTS
C_SCK0
C_MISO0
INT
C_MOSI0
RX0BF
VCC
SP1
3 PIN SMD JMP 1
3
2
P3
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
+3.3V
C_SSEL0
TX1RTS
TX0RTS
C_SCK0
C_MISO0
INT
C_MOSI0
RX0BF
VCC
SP1
3 PIN SMD JMP 1
3
2
P3
20 PIN BOX CON.
1 2
3 4
5 6
7 8
9 10
11 12
13 14
15 16
17 18
19 20
+3.3V

TP1
10K
1
3
2
ADC
+3.3V
R30
100K
TP1
10K
1
3
2
ADC
+3.3V
R30
100K

L5
LED
R21
330E
R20
330E
L6
LED
LED1
LED0
L5
LED
R21
330E
R20
330E
L6
LED
LED1
LED0
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 73




















































R11 33E
R12
1K
R27
22k
R13
15E
C11
18pF
R14
1.5K
R15 33E
R28 10K
R9
3K
R10
15E
L4
LED
+3.3V
Q1
BC557
2
1
3
D-
+3.3V
C10
18pF
VBUS
D+
CONNECT
P6
USB-B
VCC
1
D-
2
D+
3
GND
5
NC
4
R11 33E
R12
1K
R27
22k
R13
15E
C11
18pF
R14
1.5K
R15 33E
R28 10K
R9
3K
R10
15E
L4
LED
+3.3V
Q1
BC557
2
1
3
D-
+3.3V
C10
18pF
VBUS
D+
CONNECT
P6
USB-B
VCC
1
D-
2
D+
3
GND
5
NC
4

+ C1
10MF/16V
+ C5
10MF/16V
C6
0.1uF
+ C4
10MF/16V R7
100E
R6
10E
U3
LM317
VIN
3
A
D
J
1
VOUT
2
VCC
+3.3V

P8
TFT_DISPLAY
VDIGITAL
1
RESET
2
DIO
3
SCK
4
CS
5
VDISPLAY
6
NC
7
GND
8
LEDGND
9
VLRD
10
R16
33K
+3.3V
+3.3V
T_SCK0
BL_PWR
LCD RST
LCD RST
T_SSEL0
T_MOSI0
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 74




















































SP5
2

P
I
N

S
M
D
1
2
C_SSEL0
SSEL0
SP4
2

P
I
N

S
M
D
1
2
C_MOSI0
MOSI0
SP2
2

P
I
N

S
M
D
1
2
SCK0
C_SCK0
SP3
2

P
I
N

S
M
D
1
2
C_MISO0
MISO0
+3.3V
+3.3V
C14
0.1uF
R
4
3
.
3
K
SSEL0
R
5
3
.
3
K
MOSI0
U2A
74VHC08
1
2
3
1
4
+3.3V
U2C
74VHC08
9
10
8
U2B
74VHC08
4
5
6
SCK0
R
3
3
.
3
K
R
2
3
.
3
K
U2D
74VHC08
12
13
11
7
MISO0
+3.3V
C_SSEL0
C_MISO0
C_SCK0
C_MOSI0

R36
5.6K
R40 2.2E
+ C19
2
2
0
u
F
/
1
6
V
R39 150E
+ C20
1
0
u
F
/
6
.
3
V
C21
47pF
U7
MC34063A
FB
5
TCAP
3
V
C
C
6
G
N
D
4
D
C
8
P
K
7
SWC
1
SWE
2
D1
IN5819S
R37
1.2K
BD1
220uH
VCC
VCC
BL_PWR
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 75




















































+3.3V
+3.3V
C12
0.1uF
SSEL1
R
2
4
3
.
3
K
MOSI0
R
2
5
3
.
3
K
+3.3V
U6A
74VHC08
1
2
3
1
4
U6B
74VHC08
4
5
6
U6C
74VHC08
9
10
8
SCK0
R
2
2
3
.
3
K
R
2
3
3
.
3
K
U6D
74VHC08
12
13
11
7
MISO0
+3.3V
T_SSEL0
T_MISO0
T_SCK0
T_MOSI0
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 76



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.

00 Primary (default) function, typically GPIO port
01 First alternate function
10 Second alternate function
11 Reserved

The functions of PINSEL0 and PINSEL1 is described below

PERIPHERAL INTERFACING PARALLEL OUTPUT PORT
12
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 77
Pin Function Select Register 0 (PINSEL0 - 0xE002 C000)

Bit Symbol Value Function Reset Value

1:0



3:2



5:4



7:6



9:8



11:10



13:12



15:14



17:16



19:18



21:20



23:22

P0.0



P0.1



P0.2



P0.3



P0.4



P0.5



P0.6



P0.7



P0.8



P0.9



P0.10



P0.11

00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00

GPIO Port 0.0
TXD (UART0)
PWM1
Reserved
GPIO Port 0.1
RxD (UART0)
PWM3
EINT0
GPIO Port 0.2
SCL0 (I2C0)
Capture 0.0 (Timer 0)
Reserved
GPIO Port 0.3
SDA0 (I
2
C0)
Match 0.0 (Timer 0)
EINT1
GPIO Port 0.4
SCK0 (SPI0)
Capture 0.1 (Timer 0)
AD0.6
GPIO Port 0.5
MISO0 (SPI0)
Match 0.1 (Timer 0)
AD0.7
GPIO Port 0.6
MOSI0 (SPI0)
Capture 0.2 (Timer 0)
Reserved or AD1.0
GPIO Port 0.7
SSEL0 (SPI0)
PWM2
EINT2
GPIO Port 0.8
TXD UART1
PWM4
Reserved or AD1.1
GPIO Port 0.9
RxD (UART1)
PWM6
EINT3
GPIO Port 0.10
Reserved or RTS (UART1)
Capture 1.0 (Timer 1)
Reserved or AD1.2
GPIO Port 0.11

0



0



0



0



0



0



0



0



0



0



0



0
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 78



25:24



27:26



29:28



31:30







P0.12



P0.13



P0.14



P0.15


01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
Reserved or CTS (UART1)
Capture 1.1 (Timer 1)
SCL1 (I
2
C1)
GPIO Port 0.12
Reserved or DSR (UART1)
Match 1.0 (Timer 1)
Reserved or AD1.3
GPIO Port 0.13
Reserved or DTR (UART1)
Match 1.1 (Timer 1)
Reserved or AD1.4
GPIO Port 0.14
Reserved or DCD (UART1)
EINT1
SDA1 (I
2
C1)
GPIO Port 0.15
Reserved or RI (UART1)
EINT2
Reserved or AD1.5



0



0



0



0


Pin function Select register 1 (PINSEL1 - 0xE002 C004)

Bit Symbol Value Function Reset Value

1:0



3:2



5:4



7:6



9:8



11:10




P0.16



P0.17



P0.18



P0.19



P0.20



P0.21




00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11

GPIO Port 0.16
EINT0
Match 0.2 (Timer 0)
Capture 0.2 (Timer 0)
GPIO Port 0.17
Capture 1.2 (Timer 1)
SCK1 (SSP)
Match 1.2 (Timer 1)
GPIO Port 0.18
Capture 1.3 (Timer 1)
MISO1 (SSP)
Match 1.3 (Timer 1)
GPIO Port 0.19
Match 1.2 (Timer 1)
MOSI1 (SSP)
Capture 1.2 (Timer 1)
GPIO Port 0.20
Match 1.3 (Timer 1)
SSEL1 (SSP)
EINT3
GPIO Port 0.21
PWM5
Reserved or AD1.6
Capture 1.3 (Timer 1)

0



0



0



0



0



0



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 79
13:12



15:14



17:16



19:18



21:20



23:22



25:24



27:26



29:28



31:30
P0.22



P0.23



P0.24



P0.25



P0.26



P0.27



P0.28



P0.29



P0.30



P0.31
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
00
01
10
11
GPIO Port 0.22
Reserved or AD1.7
Capture 0.0 (Timer 0)
Match 0.0 (Timer 0)
GPIO Port 0.23
VBUS
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
GPIO Port 0.25
AD0.4
Reserved or Aout(DAC)
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
Reserved
GPIO Port 0.28
AD0.1
Capture 0.2 (Timer 0)
Match 0.2 (Timer 0)
GPIO Port 0.29
AD0.2
Capture 0.3 (Timer 0)
Match 0.3 (Timer 0)
GPIO Port 0.30
AD0.3
EINT3
Capture 0.0 (Timer 0)
GPO Port only
UP_LED
CONNECT
Reserved

0



0



0



0



0



0



0



0



0



0


Pin function Select register 2 (PINSEL2 - 0xE002 C014)

Bit Symbol Value Function Reset Value

1:0


-


-


Reserved, user software should not
write ones to reserved bits. The value

NA

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 80

2


3


31:4

GPIO/DEBUG


GPIO/TRACE


-

0
1

0
1

-
read from a reserved bit is not defined.
Pins P1.36-26 are used as GPIO pins.
Pins P1.36-26 are used as a Debug
port.
Pins P1.25-16 are used as GPIO pins.
Pins P1.25-16 are used as a Trace
port.
Reserved, user software should not
write ones to reserved bits. The value
read from a reserved bit is not defined.


P1.26/RTCK

P1.20/TRACESYNC



NA



General-purpose Register Map

Register
Name
Description
Acc
ess
Reset Value Address

IO0PIN
IO1PIN
IO0SET
IO1SET
IO0CLR
IO1CLR
IO0DIR
IO1DIR
FIO0DIR

FIO1DIR

FIO0MASK
FIO1MASK
FIO0PIN
FIO1PIN
FIO0SET
FIO1SET
FIO0CLR
FIO1CLR


GPIO Port 0 Pin Value Register
GPIO Port 1 Pin Value Register
GPIO Port 0 Ouptut Set Register
GPIO Port 1 Ouptut Set Register
GPIO Port 0 Output Clear Register
GPIO Port 1 Output Clear Register
GPIO Port 0 Direction Control Register
GPIO Port 1 Direction Control Register
Fast GPIO Port 0 Direction control
register
Fast GPIO Port 0 Direction control
register
Fast Mask Register for Port 0
Fast Mask Register for Port 1
Fast Port 0 Pin value register
Fast Port 1 Pin value register
Fast Port 0 Output Set register
Fast Port 1 Output Set register
Fast Port 0 Output Clear register
Fast Port 1 Output Clear register

R/W
R/W
R/W
R/W
WO
WO
R/W
R/W
R/W

R/W

R/W
R/W
R/W
R/W
R/W
R/W
WO
WO


NA
NA
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000

0x00000000

0x00000000
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000
0x00000000


0xE0028000
0xE0028010
0xE0028004
0xE0028014
0xE002800C
0xE002801C
0xE0028008
0xE0028018
0X3FFFC000

0X3FFFC020

0X3FFFC010
0X3FFFC030
0x3FFFC014
0x3FFFC034
0x3FFFC018
0x3FFFC038
0x3FFFC01C
0x3FFFC03C



Note:

1. For Direction Control Register
0 Controlled pin is input
1 Controlled pin is output

2. FIO0DIR, FIO1DIR, FIO0MASK, FIO1MASK, and etc., are some of the byte-accessible and
half-word accessible Registers.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 81
3. Byte Accessible registers (8-bit), FIO0DIR0, FIO0DIR1, FIO0DIR2, FIO0DIR3

4. Half-word Accessible Register (16-bit)
FIO0DIRL (0x3FFF C000), FIO0DIRU (0x3FFF C002)


Example

State of the output configured GPIO pin is determined by writes into the pins 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:

1. IO0DIR = 0x0000 0080 ;pin P0.7 configured as output
IO0CLR = 0x0000 0080 ;P0.7 goes LOW
IO0SET = 0x0000 0080 ;P0.7 goes HIGH
IO0CLR = 0x0000 0080 ;P0.7 goes LOW

6. IO0PIN = (IO0PIN && 0xFFFF00FF) || 0x0000A500

3. FIO0MASK = 0xFFFF00FF; //using 32-bit Fast GPIO
FIO0PIN = 0x0000A500;

4. FIO0MASKL = 0x00FF; //using 16-bit Fast GPIO
FIO0PINL = 0xA500;

5. FIO0PIN1 = 0xA5; //using 8-bit Fast GPIO


Interfacing with LED (Light Emitting Diode)

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















Fig. 12.1: LED, LED Symbol, Interfacing Circuit



LED
330O
P1.24
LED
330O
P1.24
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 82
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




























Interfacing with Seven-segment LED

_ It is an image sequence of a "LED" display
_ Composed of seven elements, Individually on or off
_ Optional DP decimal point is used for the display of non-integer numbers
_ Displaying ten decimal numerals and the six hexadecimal "letter digits" (AF)













#include <iolpc2148.h>
main: NOP
LDR R0,=IO1DIR
MOV R1,#0X00FF0000
STR R1,[R0]
LDR R0,=IO1PIN
MOV R1,#0X00550000
STR R1,[R0]
LDR R1,=0X000FFFFF
BL DELAY
LDR R0,=IO1PIN
MOV R1,#0X00AA0000
STR R1,[R0]
BL DELAY
B main

DELAY:
LDR R1,=0X000FFFFF
LOOP: SUBS R1,R1,#0X01
BGT LOOP
MOV PC,LR
END main
#include "iolpc2148.h"

void delay();

void main()
{
IO1DIR=0xFF000000;
loop:
IO1SET=0xFF000000;
delay();
IO1CLR=0xFF000000;
delay();
goto loop;
}

void delay()
{
long int j;
for(j=0;j<100000;j++);
}
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 83





















Fig.12.2: 7-Segment LED, construction and Interfacing Circuit

Seven-segment displays are found in Pocket calculators, Sign boards, Counting circuits
and etc..


Program Display 0 to 9 in 7-segment display

#include "iolpc2148.h"

unsigned char disp[10]={ 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
void delay();
unsigned int i;

void main()
{
IO1DIR=0xFF000000;
while(1)
{
for(i=0;i<10;i++)
{
IO1PIN=disp[i]<<24;
delay();
}
}
a
dp
b
c d e
f g
vcc
330 ohm
P1.24/TRACECLK
P1.27/AD0
P1.28/AD1
P1.29/TCK
P1.25/EXTIN0
P1.26/RTCK
P1.31/TRST
P1.30/TMS
20
56
52
24
64
60
32
28 b
a
dp
g
f
e
d
c
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 84
}

void delay()
{
long int i;
for(i=0;i<1000000;i++);
}


Interfacing with LCD (Liquid Crystal Display)

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.






















Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 85























Fig. 12.3: LCD Types, Character LCD, LCD pin diagram, Interfacing Circuit

The pin description for character LCD is given below.

V
CC
, GND AND V
0
- While V
CC
and V
SS
provide +5V and ground, respectively; V
0
is used for
controlling LCD contrast.

RS (Register Select) - If RS = 0, the instruction command code register is selected, allowing
the user to send a command such as clear display, cursor at home, etc. If RS = 1, the data
register is selected, allowing the user to send data to be displayed on the LCD.

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 LCDs 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.

L
C
D
VCC
1
2
10
9
8
7
6
5
4
3
16
15
14
13
12
11
RS
D5
D4
D3
D2
D1
D0
EN
RW
D7
D6
BR1
VCC 10K
VCC
BR1
P1.24/TRACECLK
P1.25/EXTINO
P1.26/AD0
P1.22/PIPESTAT1
P1.23/PIPESTST2
P1.19/TRACEPKT3
P1.20/TRACESYNC
P1.21/PIPESTST0
P1.17/TRACEPKT1
P1.18/TRACEPKT2
40
P1.16/TRACEPKT0
28
32
24
8
12
16
44
4
48
36
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 86
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

unsigned char command[5]={0x38,0x01,0x06,0x0C,0x80};
unsigned char dat[16]="Vi Microsystems";
unsigned char dat1[16]= Chennai 96 ;
int i;

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++)
{
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 87
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;
}

LCD is used in widespread applications due to the following reasons:
1. The declining prices of LCDs.
2. The ability to display numbers, characters, and graphics.
3. Incorporation of a refreshing controller into the LCD, thereby relieving the CPU of the task of
refreshing the LCD.
4. Ease of programming for characters and graphics.


Stepper Motor Interfacing

Stepper motors or Stepping motors are electromagnetic, rotary, incremental devices,
which convert digital pulses into mechanical rotation. The amount of rotation is directly
proportional to the number of pulses and the speed of rotation is relative to the frequency of
those pulses. Stepping motors are simple to drive in an open loop configuration and for their
size provide excellent torque at low speed. Although various types of stepping motor have been
developed, they all fall into three basic categories; variable reluctance (V.R), permanent magnet
and hybrid stepper motors.

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 88
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.




































In order to keep the motors 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.



Fig. 12.4: Stepper Motor and Connection Diagram
Stepper
Motor
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 89
Program Rotate the stepper motor for 360 degrees in forward diretion and 360 degrees
in reverse direction

#include<IOLPC2148.h>

void stepperfwd(unsigned long int rot);
void stepperrev(unsigned long int rot);
void stepperdelay();

void main()
{
stepperfwd(50);
stepperdelay();
stepperrev(50);
while(1);
}

void stepperfwd(unsigned long int rot)
{
int s;
IO0DIR = 0x000000F0;
for(s=0;s<rot;s++)
{
IO0PIN=0x00000090;
stepperdelay();
IO0PIN=0x00000050;
stepperdelay();
IO0PIN=0x00060060;
stepperdelay();
IO0PIN=0x000000A0;
stepperdelay();
}
}

void stepperrev(unsigned long int rot)
{
int s;
IO0DIR = 0x000000F0;
for(s=0;s<rot;s++)
{
IO0PIN=0x000000A0;
stepperdelay();
IO0PIN=0x00000060;
stepperdelay();
IO0PIN=0x00060050;
stepperdelay();
IO0PIN=0x00000090;
stepperdelay();
}
}

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 90
void stepperdelay()
{
unsigned long k;
for(k=0;k<5000;k++);
}


The benefits offered by stepping motors include:
- a simple and cost effective design
- high reliability
- maintenance free (no brushes)
- open loop (no feed back device required)
- known limit to the 'dynamic position error'





































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 91




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.


Interfacing with Switch

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.














Fig.13.1: Switch, Symbol and interfacing circuit



PERIPHERAL INTERFACING INPUT PORT
13
P1.16/TRACEPKT0
1 2
1 2
1 2
1 2
1 2
1 2
1 2
1 2
40
8
12
16
48
44
4
36 P1.23/PIPESTST2
P1.21/PIPESTST0
P1.22/PIPESTAT1
P1.19/TRACEPKT3
P1.20/TRACESYNC
P1.17/TRACEPKT1
P1.18/TRACEPKT2
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 92

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.


Program Read the keys and indicate using LEDs

#include "iolpc2148.h"

void delay();

#define SW1 IO0PIN_bit.P0_10
#define SW2 IO0PIN_bit.P0_11

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;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 93
}

void delay()
{
long int i;
for(i=0;i<10000;i++);
}


Interfacing with Sensor

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.




























Fig.13.2: IR sensor, Symbol and interfacing circuit

A
LED
2N2222A
2N2222A
1K
10K
68K 470 ohm
K
0
0
0
HI
VCC 5V
o/p


To
Microcontroller
Pin
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 94
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();

#define sensor IO0PIN_bit.P0_20
unsigned char disp[10]={ 0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
unsigned int count;

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++);
}





Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 95




Serial port is a serial communication physical interface through which information
transfers in or out one bit at a time (contrast parallel port). The name "serial" comes from the
fact that a serial port "serializes" data. That is, it takes a byte of data and transmits the 8 bits in
the byte one at a time. The advantage is that a serial port needs only one wire to transmit the 8
bits (while a parallel port needs 8). The disadvantage is that it takes 8 times longer to transmit
the data than it would if there were 8 wires. Serial ports lower cable costs and make cables
smaller.

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.







Fig.14.1: Synchronous Data Transfer


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.








Fig.14.2: Asynchronous Data Transfer



SERIAL PORT (UART)
14
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 96
SPI (Serial Peripheral Interface) and I
2
C (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.


SFRs Associated with Serial UART 0

SFR Description Access Reset Value Address

U0RBR
U0THR
U0DLL
U0DLM
U0IER
U0IIR
U0FCR
U0LCR
U0LSR
U0SCR
U0ACR
U0FDR
U0TER

Receiver Buffer Register
Transmit Holding Register
Divisor Latch LSB
Divisor Latch MSB
Interrupt Enable Register
Interrupt ID Register
FIFO Control Register
Line Control Register
Line Status Register
Scratch Pad Reg.
Auto-baud Control Register
Fractional Divider Register
TX. Enable Reg.

RO
WO
R/W
R/W
R/W
RO
WO
R/W
RO
R/W
R/W

R/W

NA
NA
0x01
0x00
0x00
0x01
0x00
0x00
0x60
0x00
0x00
0x10
0x80

0xE000 C000 (DLAB=0)
0xE000 C000 (DLAB=0)
0xE000 C000 (DLAB=1)
0xE000 C004 (DLAB=1)
0xE000 C004 (DLAB=0)
0xE000 C008
0xE000 C008
0xE000 C00C
0xE000 C014
0xE000 C01C
0xE000 C020
0xE000 C028
0xE000 C030


All of the SFRs associated with UART0 most important SFRs are explained in detail.


Baud Rate Calculation

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 97
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 users discretion. This prescaler takes the VPB clock and generates an output clock per
specified fractional requirements.


UART0 Fractional Divider Register






UART0 baudrate can be calculated as:





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


UART0 Interrupt Enable Register

The U0IER is used to enable UART0 interrupt sources.








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.



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 98
ABTOIntEn - Enables the auto-baud time-out interrupt.
0 Disable Auto-baud Time-out Interrupt.
1 Enable Auto-baud Time-out Interrupt.
ABEOIntEn - Enables the end of auto-baud interrupt.
0 Disable End of Auto-baud Interrupt.
1 Enable End of Auto-baud Interrupt.


UART0 Line Control Register (U0LCR)

The U0LCR determines the format of the data character that is to be transmitted or received.






Word Length Select
00 5-bit character length
01 6-bit character length
10 7-bit character length
11 8-bit character length
Stop Bit Select
0 1 stop bit.
1 2 stop bits (1.5 if U0LCR[1:0]=00).
Parity Enable
0 Disable parity generation and checking.
1 Enable parity generation and checking.
Parity Select
00 Odd parity
01 Even Parity
10 Forced "1" stick parity.
11 Forced "0" stick parity.
Break Control
0 Disable break transmission
1 Enable break transmission. Output pin UART0 TXD is forced to logic 0 when
U0LCR[6] is active high.
Divisor Latch Access Bit (DLAB)
0 Disable access to Divisor Latches
1 Enable access to Divisor Latches.


UART0 Line Status Register (U0LSR)

The U0LSR is a read-only register that provides status information on the UART0 TX
and RX blocks.






Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 99
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 0s) 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 1s). 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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 100

Name Description Access Reset Value Address

U1RBR
U1THR
U1DLL
U1DLM
U1IER
U1IIR
U1FCR
U1LCR
U1MCR
U1LSR
U1MSR
U1SCR
U1ACR
U1FDR
U1TER

Receiver Buffer Register
Transmit Holding Register
Divisor Latch LSB
Divisor Latch MSB
Interrupt Enable Register
Interrupt ID Reg.
FIFO Control Register
Line Control Register
Modem Ctrl. Reg.
Line Status Register
Modem Status Register
Scratch Pad Reg.
Auto-baud Control Register
Fractional Divider Register
TX. Enable Reg.


RO
WO
R/W
R/W
R/W
RO
WO
R/W
R/W
RO
RO
R/W
R/W
R/W
R/W

NA
NA
0x01
0x00
0x00
0x01
0x00
0x00
0x00
0x60
0x00
0x00
0x00
0x10
0x80

0xE001 0000 (DLAB=0)
0xE001 0000 (DLAB=0)
0xE001 0000 (DLAB=1)
0xE001 0004 (DLAB=1)
0xE001 0004 (DLAB=0)
0xE001 0008
0xE001 0008
0xE001 000C
0xE001 0010
0xE001 0014
0xE001 0018
0xE001 001C
0xE001 0020
0xE001 0028
0xE001 0030

The register description is also identical to UART0 except U1MCR and U1MSR.


UART1 Modem Control Register (U1MCR)






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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 101
1 Enable auto-CTS flow control.


UART1 Modem Status Register (U1MSR)






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 logic0 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.












Fig.14.3: RS232 connector and Interfacing Circuit



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 102
Program Program to send a character through the serial port

#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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 103
U0DLM=0x00; //U0DLM: UART0 Divisor Latch (MSB).
U0LCR=0x03; //U0LCR: UART0 Line Control Register
start:
PINSEL0=0x00000004; //Serial port enable
while((U0LSR&0x01)!=0x01); //U0RBR - UART0 Read Buffer Register
a=U0RBR;
if(a==0x61)
{
PINSEL0=0x00000000;
IO0DIR=0x00030000;
IO0PIN=0x00030000;
PINSEL0=0x00000001;
U0THR=0x41;
while((U0LSR&0x20)!=0x20);
delay();
}
else if(a==0x62)
{
PINSEL0=0x00000000;
IO0DIR=0x00030000;
IO0PIN=0x00020000;
PINSEL0=0x00000001;
U0THR=0x42;
while((U0LSR&0x20)!=0x20);
delay();
}
else if(a==0x63)
{
PINSEL0=0x00000000;
IO0DIR=0x00030000;
IO0PIN=0x00010000;
PINSEL0=0x00000001;
U0THR=0x43;
while((U0LSR&0x20)!=0x20);
delay();
}
else
{
PINSEL0=0x00000000;
IO0DIR=0x00030000;
IO0PIN=0x00000000;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 104
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;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 105
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.







































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 106




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

Interval Timer for counting internal events.
Pulse Width Demodulator via Capture inputs.
Free running timer.

LPC2148 has two timers/counters: Timer 0 and Timer 1. Timer/Counter0 and
Timer/Counter1 are functionally identical except for the peripheral base address. The features of
Timers are given below

* A 32-bit Timer/Counter with a programmable 32-bit Prescaler.
* Counter or Timer operation
* Up to four 32-bit capture channels per timer that can take a snapshot of the timer value
when an input signal transitions. A capture event may also optionally generate an interrupt.
* Four 32-bit match registers that allow: Continuous operation with optional interrupt
generation on match, Stop timer on match with optional interrupt generation., Reset timer on
match with optional interrupt generation.
* Up to four external outputs corresponding to match registers, with the following capabilities:
Set low on match.
Set high on match.
Toggle on match.
Do nothing on match.


SFRs Associated with Timer/Counter

Name Description Access Reset Value Address
T0IR
T0TCR
T0TC
T0PR
T0PC
T0MCR
T0MR0
T0MR1
T0MR2
Timer0 Interrupt Register
Timer0 Timer Control Register
Timer0 Timer Counter
Timer0 Prescale Register
Timer0 Prescale Counter
Timer0 Match Control Register
Timer0 Match Register 0
Timer0 Match Register 1
Timer0 Match Register 2
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
0
0
0
0
0
0
0
0
0
0xE000 4000
0xE000 4004
0xE000 4008
0xE000 400C
0xE000 4010
0xE0004014
0xE000 4018
0xE000 401C
0xE000 4020
TIMER
15
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 107
T0MR3
T0CCR
T0CR0
T0CR1
T0CR2
T0CR3
T0EMR
T0CTCR
T1IR
T1TCR
T1TC
T1PR
T1PC
T1MCR
T1MR0
T1MR1
T1MR2
T1MR3
T1CCR
T1CR0
T1CR1
T1CR2
T1CR3
T1EMR
T1CTCR
Timer0 Match Register 3
Timer0 Capture Control Register
Timer0 Capture Register 0
Timer0 Capture Register 1
Timer0 Capture Register 2
Timer0 Capture Register 3
Timer0 External Match Register
Timer0 Count Control Register
Timer1 Interrupt Register
Timer1 Timer Control Register
Timer1 Timer Counter
Timer1 Prescale Register
Timer1 Prescale Counter
Timer1 Match Control Register
Timer1 Match Register 0
Timer1 Match Register 1
Timer1 Match Register 2
Timer1 Match Register 3
Timer1 Capture Control Register
Timer1 Capture Register 0
Timer1 Capture Register 1
Timer1 Capture Register 2
Timer1 Capture Register 3
Timer1 External Match Register
Timer1 Count Control Register
R/W
R/W
RO
RO
RO
RO
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
RO
RO
RO
RO
R/W
R/W

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

0xE000 4024
0xE000 4028
0xE000 402C
0xE000 4030
0xE000 4034
0xE000 4038
0xE000 403C
0xE000 4070
0xE000 8000
0xE000 8004
0xE000 8008
0xE000 800C
0xE000 8010
0xE000 8014
0xE000 8018
0xE000 801C
0xE000 8020
0xE000 8024
0xE000 8028
0xE000 802C
0xE000 8030
0xE000 8034
0xE000 8038
0xE000 803C
0xE000 8070

All of the registers associated with Timer, only most important registers are explained in detail.


Interrupt Register (T0IR, T1IR)

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.





MR0 Interrupt - Interrupt flag for match channel 0.
MR1 Interrupt - Interrupt flag for match channel 1.
MR2 Interrupt - Interrupt flag for match channel 2.
MR3 Interrupt - Interrupt flag for match channel 3.
CR0 Interrupt - Interrupt flag for capture channel 0 event.
CR1 Interrupt - Interrupt flag for capture channel 1 event.
CR2 Interrupt - Interrupt flag for capture channel 2 event.
CR3 Interrupt - Interrupt flag for capture channel 3 event.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 108
Timer Control Register (T0TCR, T1TCR)

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.

Count Control Register (T0CTCR, T1CTCR)

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 Timers
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)


Capture Control Register (T0CCR, T1CCR)

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.







Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 109
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.


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 110
Calculation for the value to be loaded in timer for specified delay

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

Tins=1 3/(12 10
6
) = 0.25 s or 250 ns.

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;
}
}
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 111



In computing world, an interrupt is an asynchronous signal from hardware indicating the
need for attention or a synchronous event in software indicating the need for a change in
execution. As the name implies, an interrupt is some event, which interrupts normal program
execution.










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

INTERRUPTS
16
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 112
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.


SFRs Associated with Interrupts

Name Description Access Reset Value Address

VICIRQStatus
VICFIQStatus
VICRawIntr
VICIntSelect
VICIntEnable
VICIntEnClr
VICSoftInt
VICSoftIntClear
VICProtection
VICVectAddr
VICDefVectAddr
VICVectAddr0
VICVectAddr1
VICVectAddr2
VICVectAddr3
VICVectAddr4
VICVectAddr5
VICVectAddr6
VICVectAddr7
VICVectAddr8
VICVectAddr9
VICVectAddr10
VICVectAddr11
VICVectAddr12
VICVectAddr13
VICVectAddr14
VICVectAddr15
VICVectCntl0
VICVectCntl1
VICVectCntl2
VICVectCntl3
VICVectCntl4
VICVectCntl5

IRQ Status Register.
FIQ Status Requests.
Raw Interrupt Status Register.
Interrupt Select Register.
Interrupt Enable Register
Interrupt Enable Clear Register.
Software Interrupt Register.
Software Interrupt Clear Register.
Protection enable register.
Vector Address Register.
Default Vector Address Register.
Vector address 0 register.
Vector address 1 register.
Vector address 2 register.
Vector address 3 register.
Vector address 4 register.
Vector address 5 register.
Vector address 6 register.
Vector address 7 register.
Vector address 8 register.
Vector address 9 register.
Vector address 10 register.
Vector address 11 register.
Vector address 12 register.
Vector address 13 register.
Vector address 14 register.
Vector address 15 register.
Vector control 0 register.
Vector control 1 register.
Vector control 2 register.
Vector control 3 register.
Vector control 4 register.
Vector control 5 register.

RO
RO
RO
R/W
R/W
WO
R/W
WO
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W

0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

0xFFFF F000
0xFFFF F004
0xFFFF F008
0xFFFF F00C
0xFFFF F010
0xFFFF F014
0xFFFF F018
0xFFFF F01C
0xFFFF F020
0xFFFF F030
0xFFFF F034
0xFFFF F100
0xFFFF F104
0xFFFF F108
0xFFFF F10C
0xFFFF F110
0xFFFF F114
0xFFFF F118
0xFFFF F11C
0xFFFF F120
0xFFFF F124
0xFFFF F128
0xFFFF F12C
0xFFFF F130
0xFFFF F134
0xFFFF F138
0xFFFF F13C
0xFFFF F200
0xFFFF F204
0xFFFF F208
0xFFFF F20C
0xFFFF F210
0xFFFF F214
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 113
VICVectCntl6
VICVectCntl7
VICVectCntl8
VICVectCntl9
VICVectCntl10
VICVectCntl11
VICVectCntl12
VICVectCntl13
VICVectCntl14
VICVectCntl15
Vector control 6 register.
Vector control 7 register.
Vector control 8 register.
Vector control 9 register.
Vector control 10 register.
Vector control 11 register.
Vector control 12 register.
Vector control 13 register.
Vector control 14 register.
Vector control 15 register.
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
R/W
0
0
0
0
0
0
0
0
0
0

0xFFFF F218
0xFFFF F21C
0xFFFF F220
0xFFFF F224
0xFFFF F228
0xFFFF F22C
0xFFFF F230
0xFFFF F234
0xFFFF F238
0xFFFF F23C

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 dont happen.


Interrupt Sources

Block Flag(s)

WDT
-
ARM Core
ARM Core
TIMER0

TIMER1

UART0



UART1




PWM0
I
2
C0
SPI0

SPI1 (SSP)




Watchdog Interrupt (WDINT)
Reserved for Software Interrupts only
Embedded ICE, DbgCommRx
Embedded ICE, DbgCommTX
Match 0 - 3 (MR0, MR1, MR2, MR3)
Capture 0 - 3 (CR0, CR1, CR2, CR3)
Match 0 - 3 (MR0, MR1, MR2, MR3)
Capture 0 - 3 (CR0, CR1, CR2, CR3)
Rx Line Status (RLS)
Transmit Holding Register Empty (THRE)
Rx Data Available (RDA)
Character Time-out Indicator (CTI)
Rx Line Status (RLS)
Transmit Holding Register Empty (THRE)
Rx Data Available (RDA)
Character Time-out Indicator (CTI)
Modem Status Interrupt (MSI)
Match 0 - 6 (MR0, MR1, MR2, MR3, MR4, MR5, MR6)
SI (state change)
SPI Interrupt Flag (SPIF)
Mode Fault (MODF)
TX FIFO at least half empty (TXRIS)
Rx FIFO at least half full (RXRIS)
Receive Timeout condition (RTRIS)
Receive overrun (RORRIS)
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 114
PLL

RTC
System Control



ADC0
I
2
C1
BOD
ADC1
USB
PLL Lock (PLOCK)
Counter Increment (RTCCIF)
Alarm (RTCALF)
External Interrupt 0 (EINT0)
External Interrupt 1 (EINT1)
External Interrupt 2 (EINT2)
External Interrupt 3 (EINT3)
A/D Converter 0 end of conversion
SI (state change)
Brown Out detect
A/D Converter 1 end of conversion
USB interrupts, DMA interrupt



The structure of the interrupt registers is given below.














Software Interrupt register
0 Do not force the interrupt request with this bit number.
1 Force the interrupt request with this bit number.

Software Interrupt Clear register
0 Writing a 0 leaves the corresponding bit in VICSoftInt unchanged.
1 Writing a 1 clears the corresponding bit in the Software Interrupt register, thus
releasing the forcing of this request.

Raw Interrupt status register
0 The interrupt request or software interrupt with this bit number is negated.
1 The interrupt request or software interrupt with this bit number is negated.

Interrupt Enable register
When this register is read, 1s indicate interrupt requests or software interrupts that are enabled
to contribute to FIQ or IRQ.

Interrupt Enable Clear register
0 Writing a 0 leaves the corresponding bit in VICIntEnable unchanged.
1 Writing a 1 clears the corresponding bit in the Interrupt Enable register, thus
disabling interrupts for this request.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 115
Interrupt Select register
0 The interrupt request with this bit number is assigned to the IRQ category.
1 The interrupt request with this bit number is assigned to the FIQ category.

IRQ Status register
A bit read as 1 indicates a corresponding interrupt request being enabled, classified as IRQ, and
asserted

FIQ Status register
A bit read as 1 indicates a corresponding interrupt request being enabled, classified as FIQ, and
asserted

Vector Control registers 0-15
These are a read/write accessible registers. Each of these registers controls one of the
16 vectored IRQ slots. Slot 0 has the highest priority and slot 15 the lowest. Note that disabling
a vectored IRQ slot in one of the VICVectCntl registers does not disable the interrupt itself, the
interrupt is simply changed to the non-vectored form.






int_request/sw_int_assig - The number of the interrupt request or software interrupt assigned
to this vectored IRQ slot. As a matter of good programming practice, software should not assign
the same interrupt number to more than one enabled vectored IRQ slot. But if this does occur,
the lower numbered slot will be used when the interrupt request or software interrupt is enabled,
classified as IRQ, and asserted.
IRQslot_en - When 1, this vectored IRQ slot is enabled, and can produce a unique ISR address
when its assigned interrupt request or software interrupt is enabled, classified as IRQ, and
asserted.

Vector Address registers 0-15
These are a read/write accessible registers. These registers hold the addresses of the Interrupt
Service routines (ISRs) for the 16 vectored IRQ slots.

Default Vector Address register
This is a read/write accessible register. This register holds the address of the Interrupt Service
routine (ISR) for non-vectored IRQs.

Vector Address register
This is a read/write accessible register. When an IRQ interrupt occurs, the IRQ service routine
can read this register and jump to the value read.

Protection Enable register
This is a read/write accessible register. It controls access to the VIC registers by software
running in User mode.





Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 116
Program Use external interrupts to show the function of interrupts

#include "iolpc2148.h"
#include "intrinsics.h"

#define int0en IO0DIR_bit.P0_16
#define int1en IO0DIR_bit.P0_3
#define int2en IO0DIR_bit.P0_15

void printf(unsigned char array[]);
void intenable();
void int0(void);
void int1(void);
void int2(void);

void main()
{
VPBDIV = 0x01;
U0LCR = 0x83;
U0DLL=0x4E;
U0DLM=0x00;
U0LCR=0x03;
intenable();

while(1)
{
printf("Normal Routine ");
}
}

void printf(unsigned char array[])
{
int i;
for(i=0;array[i]!='\0';i++)
{
PINSEL0=0x00000001;
U0THR=array[i];
while((U0LSR&0x20)!=0x20);
}
}

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 117
void intenable()
{
PINSEL1_bit.P0_16=0x01;
PINSEL0_bit.P0_3=0x3;
PINSEL0_bit.P0_15=0x02;
int0en=0;
int1en=0;
int2en=0;

VICIntSelect &= ~(1<<VIC_EINT0); //Select the interrupt
VICVectAddr0 = (unsigned int)&int0;
VICVectCntl0 = 0x20 | VIC_EINT0;
VICIntEnable |= (1<<VIC_EINT0);

VICIntSelect &= ~(1<<VIC_EINT1); //Select the interrupt
VICVectAddr1 = (unsigned int)&int1;
VICVectCntl1 = 0x20 | VIC_EINT1;
VICIntEnable |= (1<<VIC_EINT1);

VICIntSelect &= ~(1<<VIC_EINT2); // IRQ on external int 2.
VICVectAddr2 = (unsigned int)&int2; // Install EINT2 in VIC addr slot
VICVectCntl2 = 0x20 | VIC_EINT2; // Enable vect int for EINT2.
VICIntEnable |= (1<<VIC_EINT2); // Enable EINT 2 interrupt.

__enable_interrupt(); // Global interrupt enable
}

#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;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 118
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;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 119
T0IR=0xFF; // reset match and capture event interrupts
T0TC=0; // Clear timer counter
T0PR= 0; // No Prescalar
T0MR0=0x07270E00 ;
T0MCR = 3; // Reset Timer Counter & Interrupt on match
T0TCR = 1; // Counting enable

VICIntSelect &= ~(1<<VIC_TIMER0); // Timer 0 intrpt is an IRQ (VIC_TIMER0 = 4)
VICVectAddr0 = (unsigned int) & TIMER0_ISR; // Install ISR in VIC addr slot 0
VICVectCntl0 = 0x20 | VIC_TIMER0; // IRQ type, TIMER 0 int enabled
VICIntEnable |= (1<<VIC_TIMER0); // Turn on Timer0 Interrupt

__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
}

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 120
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

VICIntSelect &= ~(1<<VIC_UART0); //Select the interrupt
VICVectAddr0 = (unsigned int)&SerialISR;
VICVectCntl0 = 0x20 | VIC_UART0;
VICIntEnable |= (1<<VIC_UART0);

__enable_interrupt(); //Enable Global Interrupts

while(1)
{
IO0DIR=0x00030000;
IO0SET=0x00030000;
delay();
IO0CLR=0x00030000;
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 121
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.




Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 122




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.



Fig. 17.1: Analog Vs 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.
ANALOG TO DIGITAL CONVERTER (ADC)
17
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 123
Analog to Digital Converter (ADC)

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.


Fig. 17.2: Direct Conversion ADC
Successive approximation ADCs: The conversion technique based on a successive-
approximation register (SAR), also known as bit-weighing conversion, employs a comparator to
weigh the applied input voltage against the output of an N-bit digital-to-analog converter (DAC).
Using the DAC output as a reference, this process approaches the final result as a sum of N
weighting steps, in which each step is a single-bit conversion. Initially all bits of SAR are set to
0. Then, beginning with the most significant bit, each bit is set to 1 sequentially. If the DAC
output does not exceed the input signal voltage, the bit is left as a 1. Otherwise it is set back to
0. It is kind of a binary search. For an n-bit ADC, n steps are required. SAR converters sample
at rates to 1Msps, draw low supply current, and offer the lowest production cost.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 124


Fig. 17.3: Successive approximation ADC
Integrating ADCs: A classical dual-slope converter is shown at the drawing. A current,
proportional to the input voltage, charges a capacitor for a fixed time interval T
charge
. At the end
of this interval the device resets its counter and applies an opposite-polarity (negative) reference
voltage to the integrator input. With this opposite-polarity signal applied the cap is discharged by
a constant current until the voltage at the output of the integrator reaches zero again. The time
T
discharge
is proportional to the input voltage level and used to enable a counter. The final count
provides the digital output, corresponding to the input level.

Fig. 17.4: Integrating ADC
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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 125
Sigma-delta ADCs: Sigma-delta converters, also called oversampling converters, consist of 2
major blocks: modulator and digital filter.


Fig.17.5: Sigma-Delta ADC

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.


SFRs Associated with ADC

Name Description Access Reset Value Address

AD0CR
AD1CR
AD0GDR

A/D 0 Control Register
A/D 1 Control Register
A/D 0 Global Data Register

R/W
R/W
R/W

0x0000 0001
0x0000 0001
NA

0xE003 4000
0xE006 0000
0xE003 4004
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 126
AD1GDR
AD0STAT
AD1STAT
ADGSR
AD0INTEN
AD1INTEN
AD0DR0
AD1DR0
AD0DR1
AD1DR1
AD0DR2
AD1DR2
AD0DR3
AD1DR3
AD0DR4
AD1DR4
AD0DR5
AD1DR5
AD0DR6
AD1DR6
AD0DR7
AD1DR7
A/D 1 Global Data Register
A/D 0 Status Register
A/D 1 Status Register
A/D Global Start Register
A/D 0 Interrupt Enable Register
A/D 1 Interrupt Enable Register
A/D 0 Channel 0 Data Register
A/D 1 Channel 0 Data Register
A/D 0 Channel 1 Data Register
A/D 1 Channel 1 Data Register
A/D 0 Channel 2 Data Register
A/D 1 Channel 2 Data Register
A/D 0 Channel 3 Data Register
A/D 1 Channel 3 Data Register
A/D 0 Channel 4 Data Register
A/D 1 Channel 4 Data Register
A/D 0 Channel 5 Data Register
A/D 1 Channel 5 Data Register
A/D 0 Channel 6 Data Register
A/D 1 Channel 6 Data Register
A/D 0 Channel 7 Data Register
A/D 1 Channel 7 Data Register
R/W
RO
RO
WO
R/W
R/W
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
RO
NA
0x0000 0000
0x0000 0000
0x00
0x0000 0100
0x0000 0100
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
NA
0xE006 0004
0xE003 4030
0xE006 0030
0xE003 4008
0xE003 400C
0xE006 000C
0xE003 4010
0xE006 0010
0xE003 4014
0xE006 0014
0xE003 4018
0xE006 0018
0xE003 401C
0xE006 001C
0xE003 4020
0xE006 0020
0xE003 4024
0xE006 0024
0xE003 4028
0xE006 0028
0xE003 402C
0xE006 002C



ADC Control register (AD0CR, AD1CR)





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 thats 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

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 127
010 9 clocks / 8 bits
011 8 clocks / 7 bits
100 7 clocks / 6 bits
101 6 clocks / 5 bits
110 5 clocks / 4 bits
111 4 clocks / 3 bits
PDN
1 The A/D converter is operational.
0 The A/D converter is in power-down mode.
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.


ADC Global Data Register (AD0GDR, AD1GDR)







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 V
SSA
,
while 0x3FF indicates that the voltage on Ain was close to, equal to, or greater than that on
V
REF
.
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.


ADC Global Start Register (ADGSR)





Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 128
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 thats 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.


ADC Status Register (AD0STAT, AD1STAT)

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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 129
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.


A/D Interrupt Enable Register (AD0INTEN, AD1INTEN)

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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 130
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.


A/D Data Registers (AD0DR0 to AD0DR7 and AD1DR0 to AD1DR7)

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)

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 131
AD0CR_bit.BURST = 1; //Enable Repeated Conversion
AD0CR_bit.CLKS = 0; //11 clocks/10 bit accuracy
AD0CR_bit.PDN = 1;
loop:
AD0CR_bit.SEL = 0x02;
ADC1 = (AD0DR1 >> 6)&0x3FF; //6 to 15 bits are ADC result
PINSEL0=0x00000001;
printf("\n CH0=%lx",ADC1);
printf("#");

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++);
}


Analog to Digital Converters are primarily used in industrial process measurements,
RADAR systems and Automation systems.









Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 132




The Digital to analog converters are used as digital potentiometers. So it is used in
Direct Digital Synthesizer (DDS) and most of the industrial applications. In electronics, a digital-
to-analog converter (DAC or D-to-A) is a device for converting a digital (usually binary) code to
an analog signal (current, voltage or electric charge).

Example
Input: A binary word 10010111
2
(=151
10
)
Output: Analog signal representing the weighted sum of the non- zero bits in the word.
Example: 2.96 Volts

Normally used DAC types are
/ Binary Weighted Resistor Network
/ R-2R Ladder Network
/ Multiplying DAC


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












Fig.18.1: Binary Weighted Resistor Network



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 Kirchhoffs current rule.


MSB
LSB
4
-
b
i
t

r
e
g
i
s
t
e
r
-
+
R
2R
4R
8R
I
1
I
2
I
3
I
4
R
f
I
f
I S
V
o
V
o
=
I
f

R
f
=
( I
1
+
I
2
+
I
3
+
I
4
)

R
f
DIGITAL TO ANALOG CONVERTER (DAC)
18
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 133




















Fig.18.2: R-2R Ladder Network


SFR Associated with DAC

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 * V
REF
.
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.


Program - Generate a sine wave using DAC

#include<iolpc2148.h>

int main (void)
{
DWORD i = 0;


2R
I/4
2R 2R
I
M
S
B
L
S
B
4-bit register
I/8 I/16
I/2
2R
V
s
-
+
R
f
V
o
2R
R R R
V
o
=
-R
f
( b
3
I 2
+
b
2
I 4
+
b
1
I 8
+
b
0
I 16 )
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 134
/* Initialize DAC */
PINSEL1=0x00040000;

while ( 1 )
{
DACR = (i << 6) | DAC_BIAS;
i++;
if ( i == 1024 )
{
i = 0;
}
}
return 0;
}


DAC Applications

+ Industrial Control Systems
e.g. motor speed & valves
+ Digital Audio
e.g. CD player
+ Digital Communications
e.g. digital telephone systems
+ Waveform Function Generators



















Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 135




Interfacing computer systems to the outside world is an important issue in a large
number of computer-related disciplines, from human computer interaction, to robotics, to
interactive multimedia, to computer music. In order to do this, the computer systems require
some form of sensors. A sensor is a device that measures a physical quantity and converts it
into a signal, which can be read by an observer or by an instrument. Capturing the data from
sensors is applied in industrial processes. Temperature sensor, Pressure sensor, Humidity
sensor, Acceleration sensor, Flow sensor, level sensor, velocity sensor, Solar radiation sensor,
Wind direction sensor, Fire/Smoke Sensor and proximity sensor are the types of Sensors used.


Temperature Sensor (AD590)

In an industry environment some processes work well within a certain temperature
ranges. If it beyond or reduces the limit it will affect the process output. So, it is necessary to
monitor the temperature by using temperature sensor. There are many types of temperature
sensors that will use various technologies and have different shapes. These sensors are used in
many fields in the industry and in household equipment. Appliances (ovens, refrigerators),
cars (engine, car interior), processing industries (plastic, food, chemical, car, electronics
industries.), domestic and industrial heating facilities uses temperature sensors. Thermocouple
and thermistors are the two types of temperature transducers.

A thermocouple is a junction formed from two dissimilar metals. Actually, it is a pair of
junctions. One at a reference temperature (like 0 C) and the other junction at the temperature
to be measured. A temperature difference will cause a voltage to be developed that is
temperature dependent. (That voltage is caused by something called the Seebeck effect.)
Thermocouples are widely used for temperature measurement because they are inexpensive,
rugged and reliable, and they can be used over a wide temperature range. In particular, other
temperature sensors are useful around room temperature, but the thermocouple can.
Thermistors are inexpensive, easily-obtainable temperature sensors. They are easy to use and
adaptable. Circuits with thermistors can have reasonable output voltages - not the millivolt
outputs thermocouples have. Because of these qualities, thermistors are widely used for simple
temperature measurements. They're not used for high temperatures, but in the temperature
ranges where they work they are widely used.

The AD590 is an integrated-circuit temperature transducer, which produces an output
current proportional to absolute temperature. The device acts as a high impedance constant
current regulator, passing 1mA/K for supply voltages between +4V and +30V. Laser trimming
of the chip's thin film resistors is used to calibrate the device to 298.2mA output at 298.2K
(25C). The AD590 should be used in any temperature-sensing application between -55C to
150C in which conventional electrical temperature sensors are currently employed. The
inherent low cost of a monolithic integrated circuit combined with the elimination of support
circuitry makes the AD590 an attractive alternative for many temperature measurement
situations. The features are
- Linear Current Output : 1mA/K
- Wide Temperature Range : -55C to 150C
- Two-Terminal Device Voltage In/Current Out
SENSOR INTERFACING
19
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 136
- Wide Power Supply Range : +4V to +30V
- Sensor Isolation From Case
- Low Cost















Fig.19.1: AD590, Pin diagram, Interfacing diagram


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.

Ionization smoke detectors use an ionization chamber and a source of ionizing
radiation to detect smoke. This type of smoke detector is more common because it is
inexpensive and better at detecting the smaller amounts of smoke produced by flaming fires.
Inside an ionization detector is a small amount (perhaps 1/5000th of a gram) of americium-241.
The radioactive element americium has a half-life of 432 years, and is a good source of alpha
particles. An ionization chamber is very simple. It consists of two plates with a voltage across
them, along with a radioactive source of ionizing radiation. The alpha particles generated by the
americium have the following property: They ionize the oxygen and nitrogen atoms of the air in



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 137
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.





















Fig. 19.2: MQ2 Smoke sensor and Interfacing circuit


Proximity Sensor

Proximity sensors are sensors able to detect the presence of
nearby objects without any physical contact. A proximity sensor
often emits an electromagnetic or electrostatic field, or a beam of
electromagnetic radiation (infrared, for instance), and looks for
changes in the field or return signal. The object being sensed is
often referred to as the proximity sensor's target. Different proximity
sensor targets demand different sensors. For example, a capacitive
or photoelectric sensor might be suitable for a plastic target; an
inductive proximity sensor requires a metal target.


3
2
1
4
1
1
-
+
U1A
TL034
R1
100k
R2
1k
5
6
7
4
1
1
-
+
U2B
TL034
To Microcontroller
R3
1k
R4
1k
R5
470 ohm
R6
1k
100k
POT
100k
POT
D1
3.3k
+12v
+12V
-12v
+12v
-12V
+12v
R7
POT
VCC
VCC
SMOKE SENSOR

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 138
















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



VEEPRO
20
VeePro is embroidery software, a new, powerful and easy to
use software application for embroidery industry design; which is the
main key for obtaining the most of your embroidery machine. VeePro
ensures high quality embroidery by its exciting powerful tools and
features. VeePro is software with new, fast, user-friendly and
advanced methods, which enable user to digitize a design as fast,
easy and accurate as ever. Exciting new stitch effects in VeePro lets
user create remarkable and beautiful designs. VeePro will appeal to
both new and experienced embroiderers who seek quality, reliability,
excellence and ease. VeePro allows you to produce high quality
embroidery through its easy-to-use commands and tools.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 139
Minimum System Requirements for Agilent VEE Pro

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

Pentium 133 MHz processor; 266 MHz Pentium II or higher recommended
32 MB RAM with Windows 98, 64 MB RAM with Windows NT 4.0/2000/XP, 96 MB
recommended
850 MB Hard disk free space:
CD-ROM drive
Super VGA (800x600) display or higher resolution monitor with 256 colors or more
PC keyboard and 2-button mouse (3rd button, if present, is not used)
One of the following physical connectivity options is required for the PC-to-instrument
connection:
-Agilent 82357A USB/GPIB Interface
-Agilent E5810A or E2050A/B LAN/GPIB gateway
-Agilent 82350A/B or 82341C GPIB interfaces
-USB connect to instruments supporting the TMC protocol
-Standard RS-232
-LAN connect to instruments supporting the VXI-11 protocol
-National Instruments I/O hardware using NI 488 version 1.5 (or higher)


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++)
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 140
{
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.












Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 141
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.

To start Agilent VEE Pro 6.0

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.






























To Work with Objects

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.



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 142































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.















Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 143

VEE displays objects either in icon view or open view. The iconic view conserves space in
the work area and makes programs more readable.




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.

Changing the properties of an Object

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.























Creating Data Lines Between Objects

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.)

Icon View

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 144
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.



















Deleting Data Lines Between Objects

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).




















Following figure shows the Formula object
menu open to add a data input terminal, and
another Formula object that has a second
terminal already added. The new terminal is
labeled B. If the data inputs are tied to
particular functions, as with instrument
drivers, you are given a menu of these
functions. Otherwise, the terminals are
named A, B, C... .

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 145
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.













To Loop Part of a VEE Program

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


Using Instrument Manager

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.



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 146























Collecting Random Numbers

Create a program that generates 100 random numbers and displays them. Record the total time
required to generate and display the values.


























Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 147
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.

To use the full-featured MATLAB in VEE

1. On the File menu, click the Default Preferences.
2. Click the MATLAB tab.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 148
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:

VEEs 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
VEEs Device menu, the help system is started with the main MATLAB HelpDesk window. If
your MATLAB Script object was created from VEEs 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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 149
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.

Input Pin Data

From VEE Type
To MATLAB
Type
Notes
Text Scalar

Text 1D Array


Text Array, 2D or more
Real64 Scalar
Real64 Array


Complex Scalar
Complex Array


Waveform 1D Array
character array

character array


--
double array
double array


complex array
complex array


double array
Promoted to array size (1 x n), where n is the
length of the VEE string.
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.
Not supported.
Promoted to array size (1 x1).
VEE 1D arrays are promoted to array size (m x
1). VEE arrays with 2D or greater retain original
shape.
Promoted to array size (1 x 1).
VEE 1D arrays are promoted to array size (m x
1). VEE arrays with 2D or greater retain original
shape.
VEE 1D arrays are promoted to array size (m x
1). Waveform time-base mapping is lost.


Output Pin Data

From MATLAB Type To VEE Type Notes
Empty Matrix
character array of size (1 x n)
character array of size (m x n)
character array, 3D-10D
double array of size (1 x 1)
double array of size (m x 1) or
(1 x n)
nil
Text Scalar
Text 1D Array
--
Rea64 Scalar
Real64 1D Array or
Real64 2D Array
No output container is generated.
-
Shaped as 1D array with m elements.
Not supported.
-
Automatic demotion to VEE 1D array
is selectable in object properties.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 150

double array, 2D-10D
complex array of size (1 x 1)
complex array of size (m x 1)
or (1 x n)

complex array, 2D-10D

Real64 Array
Complex Scalar
Complex 1D Array or
Complex 2D Array

Complex Array
Otherwise, a 2D array is returned.
-
-
Automatic demotion to VEE 1D array
is selectable in object properties.
Otherwise, a 2D array is returned.

MATLAB Script allows (and sometimes generates) infinity as a numeric value. VEE does
not allow values of infinity.


Using MATLAB Script in Agilent VEE

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.

Some uses of the MATLAB Script object include:
+ Letting MATLAB operate on VEE-generated data.
+ Returning results from the MATLAB Script object and using the results in other parts of the
VEE program.
+ Performing sophisticated filter design and implementation in the MATLAB Script object by
using MATLABs Signal Processing Toolbox functionality.
+ Visualizing data using 2-D or 3-D graphs.

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.
























Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 151
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.


























Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 152




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.

Real-time and embedded systems operate in constrained environments in which
computer memory and processing power are limited. They often need to provide their services
within strict time deadlines to their users and to the surrounding world. It is these memory,
speed and timing constraints that dictate the use of real-time operating systems in embedded
software.













Fig.21.1: RTOS Structure



RTOS Fundamentals


The "kernel" of a real-time operating
system ("RTOS") provides an "abstraction
layer" that hides from application software
the hardware details of the processor (or set
of processors) upon which the application
software will run. In providing this
"abstraction layer" the RTOS kernel
supplies five main categories of basic
services to application software, as seen in
Figure




Fig. 21.2: Services provided by RTOS kernel


RTOS FUNDAMENTALS
21
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 153
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.

The second category of kernel services is Intertask Communication and
Synchronization. These services make it possible for tasks to pass information from one to
another, without danger of that information ever being damaged. They also make it possible for
tasks to coordinate, so that they can productively cooperate with one another. Without the help
of these RTOS services, tasks might well communicate corrupted information or otherwise
interfere with each other. Since many embedded systems have stringent timing requirements,
most RTOS kernels also provide some basic Timer services, such as task delays and time-
outs.


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.


RTOSs vs. general-purpose operating systems


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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 154
General-computing non-real-time operating systems are often quite non-deterministic.
Their services can inject random delays into application software and thus cause slow
responsiveness of an application at unexpected times. If you ask the developer of a non-real-
time operating system for the algebraic formula describing the timing behavior of one of its
services (such as sending a message from task to task), you will invariably not get an algebraic
formula. Instead the developer of the non-real-time operating system (such as Windows, Unix or
Linux) will just give you a puzzled look. Deterministic timing behavior was simply not a design
goal for these general-computing operating systems.

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

Most RTOSs do their scheduling of tasks using a scheme called "priority-based
preemptive scheduling." Each task in a software application must be assigned a priority, with
higher priority values representing the need for quicker responsiveness. Very quick
responsiveness is made possible by the "preemptive" nature of the task scheduling.
"Preemptive" means that the scheduler is allowed to stop any task at any point in its execution,
if it determines that another task needs to run immediately. The basic rule that governs priority-
based preemptive scheduling is that at every moment in time, "The Highest Priority Task that is
Ready to Run, will be the Task that Must be Running." In other words, if both a low-priority task
and a higher-priority task are ready to run, the scheduler will allow the higher-priority task to run
first. The low-priority task will only get to run after the higher-priority task has finished with its
current work.

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 wont 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."




Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 155















Fig. 21.3. Preemptive Scheduling and Preemptive Priority

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.

The mechanisms for Intertask communication and synchronization are necessary in a
preemptive environment of many tasks, because without them the tasks might well
communicate corrupted information or otherwise interfere with each other. For instance, a task
might be preempted when it is in the middle of updating a table of data. If a second task that
preempts it reads from that table, it will read a combination of some areas of newly-updated
data plus some areas of data that have not yet been updated. [New Yorkers would call this a
"mish-mash."] These updated and old data areas together may be incorrect in combination, or
may not even make sense. An example is a data table containing temperature measurements
that begins with the contents "10 C." A task begins updating this table with the new value "99 F",
writing into the table character-by-character. If that task is preempted in the middle of the
update, a second task that preempts it could possibly read a value like "90 C" or "99 C." or "99
F", depending on precisely when the preemption took place. The partially updated values are
clearly incorrect, and are caused by delicate timing coincidences that are very hard to debug or
reproduce consistently.

An RTOS's mechanisms for communication and synchronization between tasks are
provided to avoid these kinds of errors. Most RTOSs provide several mechanisms, with each
mechanism optimized for reliably passing a different kind of information from task to task.


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 156
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.

Another kind of communication between tasks in embedded systems is the passing of
what might be called "synchronization information" from one task to another. "Synchronization
information" is like a command, where some commands could be positive, and some negative.
For eg., a negative command to a task would be something like "Please dont print right now,
because my task is using the printer." Or more generally, "I want to lock the . . . for my own use
only." A positive command would be something like "Ive detected a cardiac emergency, and I
want you to help me handle it." Or more generally, "Please join me in handling . . ."

Most RTOSs offer a semaphore or mutex mechanism for handling negative
synchronization (sometimes called "mutual exclusion"). These mechanisms allow tasks to lock
certain embedded system resources for their use only, and subsequently to unlock the resource
when theyre done. For positive synchronization, different RTOSs offer different mechanisms.
Some RTOSs offer event-flags, while others offer signals. And yet others rely on message
passing for positive synchronization as well as data passing duties.


RTOS is

Multiple events handled by a single processor
Events may occur simultaneously
Processor must handle multiple, often competing events
Wide range of RTOS systems (Simple polling through multiple interrupt driven systems)


Responsibilities of RTOS

RTOS responsible for all activities related to a task:
Scheduling and dispatching
Intertask communication
Memory system management
Input/output system management
Timing
Error management
Message management


uC/OS-II

The most common RTOS include VxWorks, Windows CE, Palm, ucLinux, pSOS, uC/OS
etc.










Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 157
MicroC/OS-II which stands for Micro-Controller Operating System (C/OS-II) is a real-
time kernel with performance comparable to many commercially available kernels. The internals
of C/OS-II are described in the book by Jean J. Labrosse entitled MicroC/OS-II, The Real-Time
Kernel, ISBN 0-87930-543-6. This book contains ALL the source code for C/OS-II. Thousands
of people around the world are using C/OS in all kinds of applications such as cameras,
medical instruments, musical instruments, engine controls, network adapters, highway
telephone call boxes, ATM machines, industrial robots, and many more. Numerous colleges and
Universities have also used C/OS and now C/OS-II to teach students about real-time
systems.

C/OS-II is a preemptive, real-time, multitasking kernel. C/OS-II has been ported to
over 45 different CPU architectures. C/OS-II is small yet provides all the services youd expect
from an RTOS: task management, time and timer management, semaphore and mutex,
message mailboxes and queues, event flags and much more. The micrium (developers of
C/OS-II) provides C/Probe. It is a Windows application that allows a user to display the value
(at run-time) of virtually any variable or memory location on a connected embedded target. The
user simply populates C/Probes graphical environment with gauges, tables, graphs, and other
components, and associates each of these with a variable or memory location. Once the
application is loaded onto the target, the user can begin C/Probes data collection, which will
update the screen with variable values fetched from the target. C/Probe retrieves the values of
global variables from a connected embedded target and displays the values in a engineer-
friendly format. The supported data-types are: booleans, integers, floats and ASCII strings.
C/Probe can have any number of data screens where these variables are displayed. This
allows to logically group different views into a product. The directory structure of C/OS is
given.


























Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 158

















C/OS-II Features

/ Preemptible priority-driven real-time scheduling.
/ 64 priority levels (max 64 tasks)
/ 8 reserved for C/OS-II
/ Each task is an infinite loop.
/ Deterministic execution times for most
/ Nested interrupts could go up to 256 levels.
/ Memory footprint is about 20KB for a fully functional kernel.
/ Supports of various 8-bit to 64-bit platforms: x86, 68x, MIPS, 8051, etc
/ Easy for development: Borland C++ compiler and DOS (optional).


Board Support Package (BSP)

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.


Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 159
C/OS-II Services



















































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 160




















































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 161
Example Program to implement 3 tasks with different delays using LEDs.

#include "includes.h"

OS_STK Task1stk[1000];
OS_STK Task2stk[1000];
OS_STK Task3stk[1000];

void Task1(void *);
void Task2(void *);
void Task3(void *);

void Task1(void *pdata)
{
IO0DIR = 0X00030000;
LPC2148BSPInit ();
while(1)
{
IO0SET = 0X00030000;
OSTimeDlyHMSM(0,0,0,750);
IO0CLR = 0X00030000;
OSTimeDlyHMSM(0,0,0,750);
}
}

void Task2(void *pdata)
{
IO1DIR = 0X00FF0000;
LPC2148BSPInit ();
while(1)
{
IO1SET = 0X000F0000;
OSTimeDlyHMSM(0,0,0,500);
IO1CLR = 0X000F0000;
OSTimeDlyHMSM(0,0,0,500);
}
}

void Task3(void *pdata)
{
IO1DIR = 0X00FF0000;
LPC2148BSPInit ();
while(1)
{
IO1SET = 0X00F00000;
OSTimeDlyHMSM(0,0,0,250);
IO1CLR = 0X00F00000;
OSTimeDlyHMSM(0,0,0,250);
}
}

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 162
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.





































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 163




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.
The concept of connected embedded CPUs sharing information is known as embedded
networking. The techniques used for embedded networking are known as Embedded
networking protocols. Despite the spread of general purpose networking ideas, there are still
many closed systems, which have very specific purposes. In this environment, a simple and
efficient protocol can be enforced without the danger of incompatibilities.


EMBEDDED NETWORKING
22
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 164
Networking Applications
Some of the applications of Embedded networking are:
- Automatic Teller Machines
- Cellular Telephones
- Computer Printers
- Home Automation
- Industrial Automation and control
- Weather Stations
- Cars
- Robots
- House hold appliances

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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 165
- 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.
The serial communication is internally divided into synchronous and asynchronous. In
synchronous systems there is a common clock, which synchronizes the data transfer. One of
the devices generates the clock, the other computer or peripheral device receives the clock.
Inter Integrated Circuit (I
2
C) and Serial Peripheral Interface (SPI) are synchronous types of
communications. In asynchronous system, the devices involved in communication uses
separate clocks. The clocks must be adjusted to an agreed frequency. Furthermore, the
receiver needs an indication that the transmission will start. Logically, the sender inserts a low
bit before the actual byte to advice the receiver that data bits are to come. Finally, a high stop bit
completes the data frame. The long distance data transfers are comes under the category of
asynchronous type of communication, eg: RS232, RS485, USB, Ethernet and CAN.

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.

Fig. 22.1: RS232 DB9 Connector Pin Details
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 166
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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 167
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.

Serial Peripheral Interface (SPI)

SPI is a serial bus standard established by Motorola and supported in silicon products
from various manufacturers. Both SPI and I
2
C provide good support for communication with
slow peripheral devices that are accessed intermittently. But SPI is better suited than I
2
C 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
I
2
C. 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 I
2
C when more than one slave is involved. But SPI tends to be simpler and more
efficient than I
2
C 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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 168




Fig. 22.2: SPI connection with single slave

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 I
2
C 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.


Universal Serial Bus (USB)

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.
SPI MASTER
SCLK
MOSI
MISO
SS
SPI SLAVE
SCLK
MOSI
MISO
SS
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 169
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.


Fig. 22.3: USB Connectors (Type A, Type B, Mini-B and Mini-A)
The Type A USB connector (downstream connector) is rectangular in shape and
is the one you use to plug into the CPU or USB hub. The Type B USB connector
(upstream connector) is more box-shaped and is the end that attaches directly to the
device. The mini-B was introduced to enable consumers to take advantage of USB PC
connectivity for the smaller devices such as cell phones and PDAs.
The mini-A port was designed to connect the new generation of smaller mobile devices.
The USB pinout is the same for either a type A or B connector; the difference is in the
shape.

Pin Signal Name Description
1 VBUS Red
2 D- White
3 D+ Green
4 GND Black
Shell Shield Drain

Fig. 22.4: USB Connector Pin Details
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.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 170
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.

An endpoint is a uniquely identifiable portion of a USB device that is the terminus of a
communication flow between the host and device. Each logical device has a unique address
assigned by the system at device attachment time. Consequently, every effective address is a
combination of the device address and the endpoint number. A USB pipe is an association
between an endpoint on a device and software on the host. Along with the device address and
endpoint number, pipes are related to bandwidth and buffer sizes. The pipes organization helps
to avoid erroneous interactions between devices.

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 V
bus
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.

Controller Area Network (CAN)

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 171
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:

1) The Arbitration Field, The Arbitration Field contains:
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.
2) The Data Field, which contains zero to eight bytes of data.
3) The CRC Field, which contains a 15-bit checksum calculated on most parts of the
message. This checksum is used for error detection.
4) An Acknowledgement Slot; any CAN controller that has been able to correctly receive
the message sends an Acknowledgement bit at the end of each message. The
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 172
transmitter checks for the presence of the Acknowledge bit and retransmits the message
if no acknowledge was detected.

Fig. 22.5: Data frames of CAN bus (CAN 2.0A, CAN2.0B)
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.


Fig. 22.6: Remote Frame and Error Frame (CAN2.0A)

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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 173
The CAN bus connector layout is recommended by CiA (CAN In Automation, an
association formed by many manufactures from many countries to define the CAN protocol) and
is pretty much the industrial standard. CAN-High and CAN-Low carrying inverted voltages noise
interferences. CAN used Low voltage differential technique to transfer the data. CAN-High
carries the voltage level of 2.75V to 4.5V for logic low and 2V to 3V for logic high and CAN-Low
carries the voltage level of 0.5V to 2.25V for logic low and 2V to 3V for logic high.









Fig. 22.7: CAN connector and pinout details

The excellent error handling mechanism, fine fault confinement, hardware
implementation of the protocol, simple transmission medium and low cost components of the
CAN protocol allows it to used in many industrial applications such as cars and truck engine
control, process control and production subsystems in industries and building automation.


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.
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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 174


Fig. 22.8: OSI Reference Model
The OSI layers may be summarized by:
1. Physical layer: Provides electrical, functional, and procedural characteristics to activate,
maintain, and deactivate physical links that transparently send the bit stream; only
recognizes individual bits, not characters or multicharacter frames.
2. Data link layer: Provides functional and procedural means to transfer data between
network entities and (possibly) correct transmission errors; provides for activation,
maintenance, and deactivation of data link connections, grouping of bits into characters
and message frames, character and frame synchronization, error control, media access
control, and flow control
3. Network layer: Provides independence from data transfer technology and relaying and
routing considerations; masks peculiarities of data transfer medium from higher layers
and provides switching and routing functions to establish, maintain, and terminate
network layer connections and transfer data between users.
4. Transport layer: Provides transparent transfer of data between systems, relieving upper
layers from concern with providing reliable and cost effective data transfer; provides end-
to-end control and information interchange with quality of service needed by the
application program; first true end-to-end layer.
5. Session layer: Provides mechanisms for organizing and structuring dialogues between
application processes; mechanisms allow for two-way simultaneous or two-way alternate
operation, establishment of major and minor synchronization points, and techniques for
structuring data exchanges.
6. Presentation layer: Provides independence to application processes from differences in
data representation, that is, in syntax; syntax selection and conversion provided by
allowing the user to select a "presentation context" with conversion between alternative
contexts.
7. Application layer: Concerned with the requirements of application. All application
processes use the service elements provided by the application layer. The elements
include library routines which perform interprocess communication, provide common
procedures for constructing application protocols and for accessing the services
provided by servers which reside on the network.
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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 175
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:
1. Start - If the wire is idle, start transmitting, else go to step 4
2. Transmitting - If detecting a collision, continue transmitting until the minimum packet
time is reached (to ensure that all other transmitters and receivers detect the collision)
then go to step 4.
3. End successful transmission - Report success to higher network layers; exit transmit
mode.
4. Wire is busy - Wait until wire becomes idle
5. Wire just became idle - Wait a random time, then go to step 1, unless maximum
number of transmission attempts has been exceeded
6. Maximum number of transmission attempt exceeded - Report failure to higher
network layers; exit transmit mode
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
No.
Wire Colour Function
1 WHITE/Orange
Transmit
Data+
2 ORANGE/White
Transmit
Data-
3 WHITE/Green
Receive
Data+
4 BLUE/White None
5 WHITE/Blue None
6 GREEN/White
Receive
Data-
7 WHITE/Brown None
8 BROWN/White None

Fig. 22.9: RJ -45 connector and pinout details

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 176
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.

ICMP protocol is used to report problems with delivery of IP datagrams within an IP
network. It reports the problems such as when the end system is not responding, when IP
network is not reachable, when the node is overloaded and when error occurs in the IP header.
The 8-bit type code identifies the types of message. In this case two types of message are
involved the ECHO request (sent by the client) and the ECHO reply (the response by the
server). Each message may contain some optional data. When data are sent by a server, the
server returns the data in the reply, which is generated. The address resolution protocol (ARP)
is a protocol used by the IP, to map IP network addresses to the hardware addresses used by a
data link protocol. The term address resolution refers to the process of finding an address of a
computer in a network. The address is "resolved" using a protocol in which a piece of
information is sent by a client process executing on the local computer to a server process
executing on a remote computer. The information received by the server allows the server to
uniquely identify the network system for which the address was required and therefore to
provide the required address. The address resolution procedure is completed when the client
receives a response from the server containing the required address.






Fig. 22.10: ICMP, ARP and MAC protocol message formats

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 177
(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:


Fig. 22.11. Ethernet frame
- 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.
Segment type
Max Number of systems per
cable segment
Max Distance of a cable
segment
10B5 (Thick
Coax)
100 500 m
10B2 (Thin Coax) 30 185 m
10BT (Twisted
Pair)
2 100 m
10BFL (Fibre
Optic)
2 2000 m


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.



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 178





































Wireless communications is one of the most active areas of technology development of
our time. This development is being driven primarily by the transformation of what has been
largely a medium for supporting voice telephony into a medium for supporting other services,
such as the transmission of video, images, text, and data. Thus, similar to the developments in
wire line capacity in the 1990s, the demand for new wireless capacity is growing at a very rapid
pace. Although there are, of course, still a great many technical problems to be solved in wire
line communications, demands for additional wire line capacity can be fulfilled largely with the
addition of new private infrastructure, such as additional optical fiber, routers, switches, and so
on. On the other hand, the traditional resources that have been used to add capacity to wireless
systems are radio bandwidth and transmitter power.

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

WIRELESS NETWORKING
23
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 179
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.
Moores 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.

Wireless communications today covers a very wide array of applications. The
telecommunications industry is one of the largest industries worldwide, with more than $1 trillion
in annual revenues for services and equipment. The largest and most noticeable part of the
telecommunications business is telephony. The principal wireless component of telephony is
mobile (i.e., cellular) telephony. The worldwide growth rate in cellular telephony is very
aggressive, and analysts report that the number of cellular telephony subscriptions worldwide
has now surpassed the number of wire line (i.e., fixed) telephony subscriptions. These
additional wireless technologies provide a basis for a very rich array of applications, including
local telephony service, broadband Internet access, and distribution of high-rate entertainment
content such as high-definition video and high-quality audio to the home, within the home, to
automobiles, and so on.

These technologies are supported by a number of transmission and channel-assignment
techniques, including time-division multiple access (TDMA), code-division multiple access
(CDMA), and other spread-spectrum systems, orthogonal frequency-division multiplexing
(OFDM) and other multicarrier systems, and high-rate single-carrier systems. These techniques
are chosen primarily to address the physical properties of wireless channels, among the most
prominent of which are multipath fading, dispersion, and interference. In addition to these
temporal transmission techniques, there are spatial techniques, notably beam forming and
spacetime coding that can be applied at the transmitter to exploit the spatial and angular
diversity of wireless channels. To obtain maximal benefit from these transmission techniques, to
exploit the diversity opportunities of the wireless channel, and to mitigate the impairments of the
wireless channel, advanced receiver signal processing techniques are of interest. These include
channel equalization to combat dispersion, RAKE combining to exploit resolvable multipath,
multi-user detection to mitigate multiple-access interference, suppression methods for co-
channel interference, beam forming to exploit spatial diversity, and space-time processing to
jointly exploit temporal and spatial properties of the signaling environment. These techniques
are all described in the ensuing chapters.


GSM (Global System for Mobile communications)

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 180
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.




























Fig.23.1. GSM Network

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)

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 181
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.













Fig.23.2. Frequency Reuse


TDMA Vs CDMA

In todays 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

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 182
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.




Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 183




















Fig.23.4. CDMA


RFID (Radio frequency identification)

Radio frequency identification is a technology similar in theory to bar code identification.
With RFID, the electromagnetic or electrostatic coupling in the RF portion of the electromagnetic
spectrum is used to transmit signals. An RFID system consists of an antenna and a transceiver,
which read the radio frequency and transfer the information to a processing device, and a
transponder, or tag, which is an integrated circuit containing the RF circuitry and information to
be transmitted.






















An RFID system may consist of
several components: tags, tag
readers, edge servers, middleware,
and application software. The
purpose of an RFID system is to
enable data to be transmitted by a
mobile device, called a tag, which is
read by an RFID reader and
processed according to the needs of
a particular application. The data
transmitted by the tag may provide
identification or location information,
or specifics about the product tagged,
such as price, color, date of
purchase, etc.
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 184
Tags shapes: Label, Ticket, Card, Glass bead, Integrated, Wristband, Button

Label - The tag is a flat, thin, flexible form
Ticket - A flat, thin, flexible tag on paper
Card - A flat, thin tag embedded in tough plastic for long life
Glass bead - A small tag in a cylindrical glass bead, used for applications such as
animal tagging (e.g. under the skin)
Integrated - The tag is integrated into the object it is tagging rather than applied as a
separate label, such as moulded into the object
Wristband - A tag inserted into a plastic wrist strap
Button - A small tag encapsulated in a ruggesdised, rigid housing

Tag Types: Active tag and passive tag/Read only tags, Write Once Read Many tags, Read
Write tags

- Passive RFID tags
+ These tags have no internal power supply.
+ The minute electrical current induced in the antenna by the incoming radio
frequency signal provides just enough power for the CMOS integrated circuit in
the tag to power up and transmit a response.
+ Device can be quite small
+ Practical read distances ranging from about 10 cm
- Active RFID tags
+ These tags have their own internal power source
+ Much more reliable and more effective
+ Practical ranges of hundreds of meters
- Read only tags contain a unique license plate number, which cannot be changed. It can
be the cheapest, because they often require the least amount of memory
- WORM Write Once Read Many - enables users to encode tags at the first instance of
use, and then the code becomes locked and cannot be changed
- Read/write allows for updated or new information to be written to the tag. These tags
are more expensive

The tag assembly process is shown below

















Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 185
Frequencies used in RFID 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 is the standard for item management air interface:

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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 186
ISO 18000-4: Parameters for air interface at 2.45 GHz
ISO 18000-5: Parameters for air interface at 5.8 GHz
ISO 18000-6: Parameters for air interface at 860-930 MHz (proposed name change UHF)
ISO 18000-7: Parameters for air interface at 433 MHz (in development)
ISO 11784 and ISO 11785 are standards for the radio-frequency identification of animals.

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.


Electronic Product Code





















Header - Tag version number
EPC Manager - Manufacturer ID
Object class - Manufacturers product ID
Serial Number - Unit ID
With 96 bit code, 268 million companies can each categorize 16 million different products where
each product category contains up to 687 billion individual units

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 187

Processes Involved in RFID System






























RFID System




















Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 188
RFID Advantages

Tags can be hidden (embedded) in most materials
No batteries needed
Different shapes and sizes
No line-of-sight required
No wear
Tags can be read even if covered with dirt or submerged
Tags are almost indestructible
Unalterable permanent serial code prevents tampering


Current Uses of RFID

+ 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.

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 189
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























Fig.23.5. Bluetooth Devices

Bluetooth Features

* Short-range radio frequency (RF)
* Instant Personal Area Network (PAN)
* Operate in the unlicensed ISM band at 2.4GHz and is capable of transmitting voice and
data
* The effective range of Bluetooth devices is 32 feet (10 meters)
* Bluetooth transfers data at the rate of 1 Mbps
* More than 1900 additional companies are members of the Bluetooth SIG
* SIG promoter members are Ericsson, IBM Corporation, Intel Corporation, Nokia, Toshiba
Corporation, 3Com Corporation, Lucent Technologies, Microsoft Corporation, Motorola Inc.
* Bluetooth is Automatic

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 190
* 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
Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 191
signal used in the respective classification is also stronger. Note that Class 3 devices are
comparatively rare.
























Fig.23.6. Piconet and Scatternet



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.



Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 192
ZigBee short history

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.




















Fig. 23.7. ZigBee Topology

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.

Although ZigBee's underlying radio-communication technology isn't revolutionary, it goes
well beyond single-purpose wireless devices, such as garage door openers and "The Clapper"
that turns light on and off. It allows wireless two-way communications between lights and

Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 193
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.


ZigBee/IEEE 802.15.4 - General Characteristics

ZigBee originates from honeybees method of communicating newfound food sources
Developed in 1998
Open global standard providing wireless networking
Standardized as IEEE 802.15.4 and taking full advantage of a powerful physical radio in
2003
Low-rate, wireless personal area networks
Technological Standard Created for Control and Sensor Networks
ZigBee is targeted at radio-frequency (RF) applications
Low data rate, long battery life, and secure networking
Transmission range is between 10 and 75 meters (33~246 feet)
The addressing space allows of extreme node densityup to
18,450,000,000,000,000,000 devices (64 bit IEEE address) using local addressing,
simple networks of more than 65,000 nodes can be configured, with reduced address
overhead
The radios use direct-sequence spread spectrum coding, which is managed by the
digital stream into the modulator.
To ensure reliable data transmission
Binary phase shift keying (BPSK) in the 868/915 MHz
Offset quadrature phase shift keying (O-QPSK) at 2.4 GHz












Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 194
Wireless Standards comparison



















































Embedded System ARM Architecture & RTOS Programming
Vi Microsystems Pvt. Ltd., Chennai 96. 195
Appendix A:

Embedded System Attributes


Mission Critical
Control System
Distributed Control
System
Small Consumer
Control System

Performance
I/O transfer rate
Memory size
Units sold
Development cost
Lifetime
Environment

Constraints
Maintenance

Repair time
Initial cycle time
Product variants

Possible examples
in this category

10 100 MIPS
10 Mb/s
16 32 MB
100 1000
$ 10M - $ 50M
20 30 years
Heat, vibration, lightning
Size, weight
Aggressive fault detect./
maintenance
30 minutes
4 10 years
5 20

Jet engines, manned
spacecraft, nuclear
power

1 10 MIPS
100 Kb/s
1 16 MB
100 10000
$ 1M - $10M
25 50 years
Dirt, fire

Size
Scheduled

4min 12 hours
2 4 years
10 10000

High-rise elevators,
train/tram/subway, air
conditioning

Up to 0.1 MIPS
1 Kb/s
1 KB
1000000+
$100K - $ 1M
10 15 years
Over-voltage, heat,
Vibration
Size, weight,
power
Never breaks

1 4 hours
0.1 4 years
3 10

Automotive
Auxiliaries,
consumer

You might also like