You are on page 1of 37

CHAPTER 1

INTRODUCTION
You read about it everywhere: distributed computing is the next revolution, Perhaps relegating our desktop computers to the museum. But in fact the age of distributed computing has been around for quite a while. Every time we withdraw money from an ATM, start our car, use our cell phone, or microwave our dinner, microprocessors are at work performing dedicated functions. These are examples of just a very few of the thousands of embedded systems. Until recently the vast majority of these embedded systems used 8- and 16-bit microprocessors, requiring little in the way of sophisticated software development tools, including an Operating System (OS). But the 32-bit processors are now driving an explosion in high-volume embedded applications. And a new trend towards integrating a full system-on-a-chip (SOC) promises a further dramatic expansion for 32-bit embedded applications as we head into the 21st century. Aerospace companies were the first end-markets for embedded systems, driven by military and space applications. But this market has never developed the growth potential of the newer commercial applications. In the past five years, the major end-markets for embedded systems have been telecommunications, computer networking, and office equipment. But, now we see consumer and automotive electronics as major emerging markets. And looming on the horizon is the suspected wave of networked appliances, with Sun Microsystems, IBM, Microsoft and others targeting products and standards; envisioning billions of embedded network connections running embedded JAVA applications across a network.

CHAPTER 2
HISTORY
The first recognizably modern embedded system was the Apollo Guidance Computer, developed by Charles Stark Draper at the MIT Instrumentation Laboratory. Each flight to the moon had two. They ran the inertial guidance systems of both the command module and LEM.

Fig:-2.1

At the project's inception, the apollo guidance computer was considered the riskiest item in the apollo project. The use of the then new monolithic integrated circuits, to reduce the size and weight, increased this risk. The first mass-produced embedded system was the guidance computer for the Minuteman missile in 1961. It was the Autonetics D-17 guidance computer, built using discrete transistor logic and a hard disk for main memory. When the Minuteman II went into production in 1966, the D-17 was replaced with a new computer that used integrated circuits, and was the first volume user of them. Without this program, integrated circuits might never have reached a usable price-point. The crucial design features of the Minuteman computer were that its guidance algorithm could be reprogrammed later in the program, to make the missile more accurate, and the computer could also test the missile, saving cable and connector weight.

CHAPTER 3
EMBEDDED APPLICATION DEVELOPMENT CHARACTERISTICS
What characterizes an embedded system? Usually it means that there are a set of pre-defined, specific functions to be performed, and that the resources available (e.g., memory, power, processor speed, computational functionality) are constrained. Often, though not always, the application will run out of ROM on a microprocessor. This, in comparison to a desktop computer, which is a general-purpose processor and support system designed for a wide range of applications. The range of embedded software is much broader than desktop software, where a handful of applications (word processors, spreadsheets, games, and so on) make up the vast majority of applications.

Embedded tools are now catching up with Windows GUI, object oriented programming and client/server architectures. These new tools are stressing ease-of-use and enabling team disciplines to work on the same project from different locations across the enterprise.

Driving this need for tools is a basic fact of the embedded market. With increased competition, companies supplying embedded products cannot afford schedule slippage that result in missed market opportunities. Increasing the productivity of engineers and programmers has become the critical factor in bringing embedded products to market quickly and at reasonable cost. The most developed segment of the embedded tools market are the off-the-shelf real-time operating systems (RTOSs), including their support programming tools: source level debuggers, integrated development environment, and compilers.

The commercial RTOS market is highly fragmented with offerings from dozens of vendors, supplying products for many different microprocessors. This fragmentation is caused by three factors. First, there are dozens of different microprocessors optimized for different embedded applications. A different version of the RTOS, with a corresponding set of development tools, must be written for each microprocessor. Second, different applications offer widely variable sets of available programming resources. Some RTOSs are optimized for more resource constrained environments, and others are aimed at less constrained environments. And third, different end market applications have different needs and levels of complexity. Some RTOSs offer a wide range of available services, while others are simpler. A single RTOS cannot provide the optimal solution for every application. Hardware: Good software design in embedded systems stems from a good understanding of the hardware behind it. All embedded systems need a microprocessor, and the kinds of microprocessors used in them are quite varied. A 3

list of some of the common microprocessors families are: The Zilog Z8 family, Intel 8051/X86 family, Motorola 68K family and the power PC family. For processing of information and execution of programs, embedded system incorporates microprocessor or micro- controller. In an embedded system the

microprocessor is a part of final product and is not available for reprogramming to the end user. An embedded system also needs memory for two purposes, to store its program and to store its data. Unlike normal desktops in which data and programs are stored at the same place, embedded systems store data and programs in different memories. This is simply because the embedded system does not have a hard drive and the program must be stored in memory even when the power is turned off. This type of memory is called ROM. Embedded applications commonly employ a special type of ROM that can be programmed or reprogrammed with the help of special devices. UMS Hardware: A common obstacle for developers has been the need to develop different sets of hardware and software for different devices. An intelligent washing machine uses a hardware chip different from that used by an intelligent wrist watch. In addition, the software running on the hardware chip is different. This often results in increased costs and time taken for development. The Universal Micro System(UMS) from cradle technologies is a solution for this problem. UMS is a general purpose chip built around a simple instruction set. It can be used to develop applications for embedded devices because all the functionality required for a specific device can be modeled in the software. Since the major functionality provided in UMS is through software, the processor and memory units must be very fast and the input, output units must be programmable and versatile. UMS uses a large number of high speed, low power and small RISC based processors on a single chip. Each processing element coupled with two digital signal processors form a multi stream processor(MSP), which processes oluminous chunks of data. Developing on UMS represents a significant infrastructure cost savings, dramatic decrease in time to market and an unprecedented opportunity to combine many functions and redefine products in the market.

PROG I/O P R O G I / O P R O G I / O P R O G I / O

PROG I/O

PROG I/O P R O G I / O P R O G I / O P R O G I / O

M S P

M S P S

M S

M S P

M S P

M S P

M S P

MEMORY

MEMORY

DRAM CONTROL M CLOCKS, DEBUG S P

MEMORY M S P M S P M S P M S P

MEMORY M S P M S P M S P

PROG I/O PROG I/O

PROG I/O

Fig:-3.1

NVRAM

DRAM

Software:
Embedded software has grown complex and pervasive enough to attract the attention of computer scientists. Embedded softwares main task is to engage the physical world interacting directly with sensors & actuators. The most pressing problem is how to adapt existing software techniques to meet the challenges of the physical world. Software for embedded systems must handle problems beyond those found in application software for desktops or mainframe computers. Embedded software often has several things to do at once respond to external events, cope with unusual conditions without human intervention while being subjected to deadlines. So embedded software is harder to design. Embedded systems are increasingly networked which introduced significant complications such as downloadable modules that dynamically reconfigure the 5

system. Moreover, consumers demand ever more elaborate functionality which greatly increases software complexity. These systems can no longer be designed by a single engineer, fine tuning tens of kilobytes of assembly code.

Embedded software design is art as much as it is science. We must know how fast our system operates and know how critical it is to meet each deadline. If deadlines are absolute, then it is a hard real time system else it is a soft real time system. Functionality has steadily shifted from hardware to software. C has become the language of choice for embedded programmers, because it has the benefit of processor independence. Languages such as C++, Java are also used. Home devices will flourish best if they present a uniform API to application programmers, and an ideal interface is Java. Open Service Gateway Initiative(OSGI) , a java based system that combines services with event on security mechanisms, is defining a set of open standard software application interfaces for building Open Service Gateways including Residential Gateways . Embedded Graphical User Interfaces (GUI) are growing more elaborate day by day. Developers now have to contend with such arcana as a colour pallet. In some applications, an embedded GUI has to compete with mechanical controls. In luxury cars, for e.g, Graphical displays are starting to replace mechanical speedo meters and tacho meters. Visualization tools are designed to find bugs that are hard to find with the usual Breakpoint and explore debugging paradigm. They work beautifully on Heisenberg bugs so called because they disappear when we start looking for them.

Any source code written in C or C++ or assembly language must be converted into an executable image that can be loaded onto a ROM chip. For this purpose three distinct steps are involved:1) Cross compiled or assembled to generate object files. 2) Object files must be linked into a relocatable program. 3) Physical memory address must be assigned to the relocatable program.

RTOS:
To run any software we need operating system. Embedded systems do not require a complete operating system, which may make the system bulky, but only the basic functionalities of the operating system in a real time environment RTOS. Off-the-shelf operating systems for these systems began to appear in the late 1970s, and today several dozen viable options are available. Embedded operating systems are available in variety of flavours: Windows NT, LINUX, Windows CE 3.0, Palos, QNX, ROMDOS, JBED, RT kernel, Tiny BIOS, Turbo task, Nucleus plus/Tasking, Diamond, ThreadX etc. Out of these , a few major players have emerged , such as Vxworks, PSOS, nuculeus, windows CE, ThreadX and Linux. Inferno and Chai are the two popular environments that are used to develop applications. 6

Embedded Databases:
Embedded Databases are in software applications and in hardware devices, both mobile and fixed. The purpose of Embedded Database is data storage and retrieval with minimum intervention and minimum system impact. The rapid increase in the number of Telecomputers, the explosive growth of E-commerce and general migration to wireless technologies have put Embedded Database development on the IT short list. In a world of mobile computers and smart devices , size matters because memory and storage are very limited. A key factor is a small memory foot print. Embedded database vendors and developers tend to focus on smallness of their achievements. Sybases Ultra Lite, a version of SQL which is anywhere portable database has a foot print of 50 kilobytes.

Firmware:
Many authors use software and firmware in the same sense. Actually firmware consists of microcode programs executed from very high speed control storage. Commonly used object programs placed in ROMs and PROMs are also some times referred to as firmware. The problem with any approach to the field firmware updates is that if the upgrade contains a flaw, the target system may become an expensive doorstop. Many of the pitfalls are obvious and straight forward, but some insidious defects dont appear until after a product has been deployed. Any well designed firmware upgrade system must be able to recover from user errors and other catastrophic events to the fullest extent possible. The best way to accomplish this is to implement a fundamentally sound firmware update strategy that avoids these problems entirely. A microprogrammer is a system level description of how an embedded system beheves before, during and after the firmware update process. This is designed to help avoid many of the problems to downloadable firmware. Flexware is a flexible firmware development environment. COMPONENTS NEEDED: The components needed for the development of Embedded Applications are: 1. Micro Controller or Microprocessor. 2. Real-time Operating System. 3. A language for coding. 4. Machine code generator. 5. Debugger.

MICROCONTROLLER v/s MICROPROCESSOR:


Microprocessor and Microcontroller are two popular terms in world of computer. However, microprocessor and microcontroller has different functions and features. 7

Microprocessors generally require external components or circuits to implement program memory, RAM memory and Input/Output. Intel's 8085, 80386 and Pentium are examples of

microprocessors.Microcontrollers incorporate program memory, RAM memory and input/output port into one chip.

One of the main differences is that microcontrollers are usually designed to perform a small set of specific functions, for example as in the case of a Automatic Braking System which performs a small set of input processing functions, whereas microprocessors tend to be designed to perform a wider set of general purpose functions. For example, microcontrollers are widely used in modern cars where they will each perform a dedicated task, i.e. a microcontroller to regulate the brakes on all four wheels, or a microcontroller to regulate the car air conditioning, or a microcontroller for automatic gate systems.

These microcontrollers will perform few other tasks (if any) other than those specified. Compare to a microprocessor in a PC which performs a wide range of tasks related to the general requirements of a PC such as performing the necessary calculations for a very wide set of software applications, performing Input/Output for the main subsystems, peripheral control and etc.

TYPES OF MICROCONTROLLERS:
The predominant family of microcontrollers are 8-bit types since this word size has proved popular for the vast majority of tasks the devices have been required to perform. The microcontroller family would have a common instruction subset but family members differ in the amount, and type, of memory, timer facility, port options, etc. possessed, thus producing cost-effective devices suitable for particular manufacturing requirements. There are 4 major 8 bit micro controllers. They are Freescale's 6811, Intel's 8051, Zilog's Z8 and PIC 16x from Microchip Technology. Each of these Microcontrollers have a unique set of instruction set and register set; therefore they are not compatible with each other.

Fig:3.2

8051 MICROCONTROLLER
The 8051 is the first microcontroller of the MCS-51 family introduced by Intel Corporation at the end of the 1970s. The 8051 family with its many enhanced members enjoys the largest market share, estimated to be about 40%, among the various microcontroller architectures. The architecture of the 8051 family of microcontrollers is referred to as the MCS-51 architecture, or sometimes simply as MCS-51. The microcontrollers have an 8-bit data bus. They are capable of addressing 64K of program memory and a separate 64K of data memory. The 8051 has 4K of code memory implemented as on-chip Read Only Memory (ROM). The 8051 has 128 bytes of internal Random Access Memory (RAM). It has two timer/counters, a serial port, 4 general purpose parallel input/output ports, and interrupt control logic with five sources of interrupts. Besides internal RAM, the 8051 has various Special Function Registers (SFR), which are the control and data registers for on-chip facilities

Fig:3.3

Machine code generator:


The source code is written in a particular language like C/C++. This has to be then used to generate the code for the particular microprocessor. The machine specific code is then burnt into the chip(ROM). The microprocessor takes the instructions from the ROM and executes them to produce the desired effect.

10

CHAPTER 4
REAL-TIME OPERATING SYSTEM
What does real-time mean when used in the context of an operating system? Simply put, this means that the embedded application can and will respond to external events in real time, as opposed to waiting for some other task or process to complete its operation. This is made even more confusing by the use of the terms hard real-time and soft real-time.

Hard real-time means an activity must be completed always by a specified deadline (which may be a particular time or time interval, or at the arrival of some event), usually in tens of microseconds to few milliseconds. Some examples include the processing of a video stream, the firing of spark plugs in an automobile engine, or the processing of echoes in a Doppler radar.

Soft real-time applies to those systems that are not hard real-time, but some sort of timeliness is implied. That is, missing the deadline will not compromise the systems integrity, but will have a deleterious effect. Examples of this type of system are point of sale (POS) systems in retail stores, ATMs and other credit card machines, and PDAs. When a POS system can not read the bar code because the item was scanned too quickly, the system simply indicates an error, and the item will be scanned again for identification. Further confusing the notion of hard and soft real-time is increased processor speeds. When the processor speed increases, interrupts are processed more quickly. More importantly, the interrupt window in which interrupts are disabled keeps shrinking and this will improve the timeliness of response. So soft real-time performance may improve just as a function of processor speed. But countering this trend is the increasing complexity of the applications, requiring more processing to be done at interrupts, and the blurring of the hardware-software interface. But be they hard or soft, real-time (or perhaps a general term should be embedded) OSs have four characteristics in common that differentiate them from desktop or mainframe OSs.

SERVICING AND SCHEDULING:


BOUNDED INTERRUPT SERVICING:

There is a maximum allowable time that the system can be diverted to process an interrupt. The interrupt service routine must do the absolute minimum processing and terminate. 11

PRIORITY BASED SCHEDULING:

In a real-time system, all tasks are assigned a level of priority, viz a viz each other. This priority may be based on any number of criteria (including run time). This implies that tasks do not execute just because they are ready, but rather because they are the highest priority task that is ready.

PREEMPTIVE TASKS:

All tasks and routines must be constructed in such a way that they can be pre-empted by some higher priority task or routine becoming ready.

SCALABILITY:

The OS services provided are not monolithic. Rather, they are provided as a set of modules or libraries. The services needed for an application are included in the build by simply setting flags at the time of the application build; or, in the case of libraries, by having the linker pull in the services used by the application; or by using conditional compilation to scale the OS.

But, besides these four, there are other differences between real-time and desktop OSs that have more to do with the needs of the end application, the needs of the embedded developer, and the restrictions placed on the application by the resources available. The most obvious is the RAM requirement. Considering the volumes and tight end user pricing of most embedded systems, RAM is a very precious commodity. The OS must use this memory efficiently while preventing fragmentation, recovering RAM when tasks are terminated, requiring the minimum amount of RAM when tasks are created, and providing for efficient stack and heap structures.

Probably just as important are the scheduling algorithms, since these are at the heart of system performance. There are wide varieties of algorithms that have been developed and, depending on the end application, the developer would want to choose the one satisfying the response requirements while being the stingiest on resources. Some of the algorithms developed include:

HEURISTIC:

At any time, the task with the earliest deadline will be executed. This algorithm is efficient, but it may not find a feasible schedule even if one exists. 12

ROUND ROBIN:

Each task is assigned a fixed amount of processor time, and when that time is up, the next task executes.

SIMPLE PRIORITY:

The user assigns a priority at the time of thread creation. The next thread to execute is based on the priority of the ready thread. In a large system, it can be difficult for the user to decide the priorities of each thread.

RATE MONOTONIC:

The tasks of the program are assigned priorities in descending order according to the length of the period. The task with the shortest period has the highest priority, and the task with the longest period has the lowest priority. In its simplest form, it does not provide support for sporadic events. Modifications have been proposed, such as polling, priority exchange algorithm, and deferrable server algorithm.

DEADLINE MONOTONIC SCHEDULING: This is close to the Rate Monotonic but accommodates sporadic tasks. Not as obvious, but just as important, are mechanisms that have been created to synchronize and communicate between tasks. While also found in non-RTOSs, these mechanisms take on a critical role in embedded systems due to the requirements on response and the scarcity of resources. The well known synchronization mechanisms are semaphores, mutexes, and condition variables, with message queues and mailboxes being among the more common task communication devices. But just having these mechanisms is not sufficient. These mechanisms must be designed in such a way as to take a bounded amount of time for worst case situations. For example, if a set of tasks have to wait for a semaphore in a wait queue, the wait queue should not be singularly linked, since removing a task from the list will require traversing the entire list of waiting tasks. Some more efficient algorithm, with bounded worst case performance, must be used.

An example of a commercial RTOS architecture is given in Figure 1 for pSOSystem from Integrated Systems, Inc.

13

SYSTEM TASK

USER TASK

USER TASK

C/C++ INTERFACE

pSOS+

TCP/IP

RPC

DEBUG AGENT

FILE SUPPOR T

C LIBRARY

OTHER COMPONENET S

INERRUPT HANDLER Fig:4.1

DRIVERS

pSOSystem uses a modular architecture, containing the pSOS+ real-time, multi-tasking kernel and a collection of companion software components and libraries. These components are delivered as black boxes, remaining unchanged from application to application. This assures high reliability to the end user. Example structure of an

14

embeddedsystem.

Service layer

Creation termination scheduling

Communication synchronization

Utility service

System calls

Processor management List management Machine layer

dispatching

List management

Kernal mechanism

Context switch

Interrupt handling

Timer handling

Machine layer (assembly code):Directly interacts with hardware, not visible at the
user level primitives mainly deal with context switch, interrupt handling, timerhandling

List management layer: Tasks having the same state are enqueued in lists basic
primitives for inserting and removing tasks to an from list. Processor management: scheduling and dispatching operations

Service layer: Provides all services visible at the user level as a set of system calls.
task creation, task abortion, suspension of periodic instances, activation and suspension of aperiodic instances, system inquiry operations

Task Control Block (TCB) contains static and dynamic information, e.g.memory address corresponding to he first instruction of a task memory address corresponding to the first instruction of a task task type (periodic, aperiodic, sporadic) task criticalness (hard, soft, non-real time) value which represents the importance of the task current state (ready, running, idle, waiting, ..) worst case execution time

15

relative deadline,absolute deadline computed by the kernel at the arrival time. Pointer to process stack (Process Control Block), where the context is stored pointer to precedence graph pointer to a list of shared resources.

16

CHAPTER 5
DESIGN ISSUES FOR EMBEDDED SYSTEMS:
Embedded Systems are, if nothing else, characterized by constraints such as response, size, performance, costs, and so on. And it is optimizing for these constraints (or rather perhaps working within them) that makes designing an embedded system a difficult task. Numerous questions have to be answered before the design even begins: What are the worst case performance requirements for each activity? What are the number and complexity of activities to be performed? How should these activities be distributed amongst the software tasks so that the processor load is balanced (and thereby get the best cost/performance out of the processor selection)? What is the degree of coupling of these tasks (critical deadlines, type of data flow among tasks, event interdependencies)? How much RAM and ROM does the hardware design provide? How much RAM and ROM will be consumed for the specific set of tasks, ISRs, queues, and so on? How much buffer space should be allocated for stack usage?

Over the years, the articles in Embedded Systems Programming magazine have dealt with many, if not most, of the issues facing embedded systems designers. A number of the more commonly faced issues are summarized here.

TIME CONSTRAINTS:
Real-time operating systems bow to a combination of time specific constraints. Some routines must execute at precisely fixed intervals, while other routines are not bound to a critical time alignment. The most critical task of an embedded programmer is to characterize each of the actions to be performed so he will know how to assign priority and resources to that action in order that the overall system performance objectives are met. To aid in this task, it is helpful to break the actions in an embedded system down into the following four task groups: 1. Time critical task routines are those that must occur at a fixed rate with a minimum startup latency (e.g., servicing an A/D converter).

2. Time sensitive task routines are different from time critical tasks in that they can tolerate a large latency before being serviced. Like time critical task routines, they may also occur at fixed rates or they may be 17

initiated at random intervals, but are guaranteed to execute no more frequently than some fixed rate by the task handler itself.

3. Idle task routines are important background operations, and they execute as frequently as pos more or less random interval when it is convenient.

4. Mainline tasks routines interpret the user commands, perform non-real-time to the time sensitive and idle task service routines.

functions, and make calls

SAFETY:
While the reliability of hardware has improved dramatically, when the mission of the embedded system is critical, the embedded designer must build tests of the processor and memory into the application. There are a variety of ways that this can be accomplished.

Probably the first and simplest safety technique learned by many embedded programmers consists of filling unused program memory with either halt instructions or illegal instructions. This technique guards against illegal jumps outside of the program space and provides cheap insurance.

Another common protection is to use buffers that guard against stack underflow/overflow or the corruption of a task's stack. Many of the commercial RTOSs now contain facilities and functions that support stack checking.

To verify the integrity of a program or data stored in ROM, a simple ROM test should be included as well a watchdog timer to prevent the software from getting caught in a loop.

It is also well known that a rogue pointer, for example, can lead to wholesale corruption of memory. So how does one protect against the corruption of program data? One technique is the redundant storage of critical variables, and comparison prior to being used. Another is the grouping of critical variables together and keeping a CRC over each group.

DEVICE DRIVERS:
It is well known that writing efficient device drivers requires knowledge of both hardware and software. The resulting device drivers become the keys to embedded system performance since they are called repeatedly,

18

and therefore dictate real-time performance in terms of response time, and utilization of memory and other system resources.

INTERRUPT SERVICE ROUTINES:


Using interrupt processing is a powerful technique that is often more appropriate than using software loops to continuously poll peripheral devices. However, the compiler does not dictate interrupt-processing strategy, and most RISC processors do very little in response to interrupts. These constraints place a burden on the embedded developer in that he must decide which interrupt architecture is best. Some approaches are to save the interrupted context on a memory stack. Another is to preserve the context in a cache, be it onchip registers (if there are a lot of them to use) or off-chip memory. To simplify debugging, it is best to keep ISRs short.

STORAGE ALLOCATION:
One important feature to be considered in the selection of an RTOS or embedded system design is storage allocation. Ill-designed dynamic storage allocation can be wasteful for two reasons. First, allocating memory from the heap can be both slow and non-deterministic. The time it takes for the memory manager to search the free-list for a block of the right size may not be bounded. Second, one may create the possibility of a memory allocation fault caused by a fragmented heap. One typical solution is to statically declare all objects up front and get rid of dynamic allocation. However, this can waste storage since the objects always exist and take space. Whilst difficult, the apparently conflicting goals of a dynamic storage allocator can be achieved.

OPTIMIZING PERFORMANCE:
Writing embedded code that runs efficiently brings about a whole new set of rules. Often optimizing for speed and size opposing design goals-an improvement on one often degrades the other. In trying to achieve this balance, the article promotes the use of three techniques: the judicious use of the optimization options found with most embedded cross-platform compilers (for example, eliminating redundant code, or replacing operations with equivalent but faster operations, or unrolling loops, optimizing the use of registers, or removing code segments that the compiler knows cannot be reached) 19

the mix of fixed and floating-point operations and the employment of user optimizations, making the most out of available resources.

DEBUGGING MEMORY PROBLEMS:


Since many RTOSs and/or embedded microprocessors do not support memory protection, tracking down software memory bugs can become a serious debugging problem. In attacking this problem, it is best to categorize the problem by the type of Memory affected. In general, they fall into three categories: Global memory bugs: those bugs that result in corruption of global memory data areas. Stack memory bugs: these often cause a complete failure of the program execution; they are the hardest to track down as they are often a function of external events and the current state of the stack. Dynamically allocated memory bugs: examples are, heap memory allocated by a malloc service; or problems caused by writing past the boundaries of an allocated memory block or using one that is no longer allocated.

20

CHAPTER 6
8051 ARCHITECTURE

The Intel 8051 is an 8-bit microcontroller which means that most available operations are limited to 8 bits. Some of the features that have made the 8051 popular are:

8-bit data bus 16-bit address bus 32 general purpose registers each of 8 bits 16 bit timers (usually 2, but may have more, or less). 3 internal and 2 external interrupts. Bit as well as byte addressable RAM area of 16 bytes. Four 8-bit ports, (short models have two 8-bit ports). 16-bit program counter and data pointer

PIN DESCRIPTION OF 8051 PIN 9: PIN 9 is the reset pin which is used reset the microcontrollers internal registers and ports upon starting up.2 machine cycle should be high at this pin. PINS 18 & 19: The 8051 has a built-in oscillator amplifier hence we need to only connect a crystal at these pins to provide clock pulses to the circuit. PIN 40 and 20: Pins 40 and 20 are VCC and ground respectively. The 8051 chip needs +5V 500mA to function properly. PINS 29, 30 & 31: As described in the features of the 8051, this chip contains a built-in flash memory. In order to program this we need to supply a voltage of +12V at pin 31. If external memory is connected then PIN 31, also called EA/VPP, should be connected to ground to indicate the presence of external memory. PIN 30 is called ALE (address latch enable), which is used when multiple memory chips are connected to the controller and only one of them needs to be selected. PIN 29 is called PSEN. This is "program select enable". In order to use the external memory it is required to provide the low voltage (0) on both PSEN and EA pins.

21

Fig:6.1

PORTS There are 4 8-bit ports: P0, P1, P2 and P3. PORT P1 (Pins 1 to 8): The port P1 is a general purpose input/output port which can be used for a variety of interfacing tasks. The other ports P0, P2 and P3 have dual roles or additional functions associated with them based upon the context of their usage.

PORT P3 (Pins 10 to 17): PORT P3 acts as a normal IO port, but Port P3 has additional functions such as, serial transmit and receive pins, 2 external interrupt pins, 2 external counter inputs, read and write pins for memory access. PORT P2 (pins 21 to 28): PORT P2 can also be used as a general purpose 8 bit port when no external memory is present, but if external memory access is required then PORT P2 will act as an address bus in conjunction with PORT P0 to access external memory. PORT P2 acts as A8-A15, as can be seen from fig PORT P0 (pins 32 to 39) PORT P0 can be used as a general purpose 8 bit port when no external memory is present, but if external memory access is required then PORT P0 acts as a multiplexed address and data bus that can be used to access external memory in conjunction with PORT P2. P0 acts as AD0-AD7, as can be seen from above fig 6.1

22

REGISTERS

THE ACCUMULATOR

The Accumulator, as its name suggests, is used as a general register to accumulate the results of a large number of instructions. It can hold an 8-bit (1-byte) value and is the most versatile register the 8051 has due to the shear number of instructions that make use of the accumulator. More than half of the 8051s 255 instructions manipulate or use the accumulator in some way.

THE "R" REGISTERS

The "R" registers are a set of eight registers that are named R0, R1, etc. up to and including R7.These registers are used as auxillary registers in many operations.

THE "B" REGISTER

The "B" register is very similar to the Accumulator in the sense that it may hold an 8-bit (1-byte) value.The "B" register is only used by two 8051 instructions: MUL AB and DIV AB. Thus, if you want to quickly and easily multiply or divide A by another number, you may store the other number in "B" and make use of these two instructions.Aside from the MUL and DIV instructions, the "B" register is often used as yet another temporary storage register much like a ninth "R" register.

THE DATA POINTER (DPTR)

The Data Pointer (DPTR) is the 8051s only user-accessable 16-bit (2-byte) register. The Accumulator, "R" registers, and "B" register are all 1-byte values. DPTR, as the name suggests, is used to point to data. It is used by a number of commands which allow the 8051 to access external memory. When the 8051 accesses external memory it will access external memory at the address indicated by DPTR.

THE PROGRAM COUNTER (PC):

The Program Counter (PC) is a 2-byte address which tells the 8051 where the next instruction to execute is found in memory. When the 8051 is initialized PC always starts at 0000h and is incremented each time an instruction is executed. It is important to note that PC isnt always
23

incremented by one. Since some instructions require 2 or 3 bytes the PC will be incremented by 2 or 3 in these cases.The Program Counter is special in that there is no way to directly modify its value.
THE STACK POINTER (SP)

The Stack Pointer, like all registers except DPTR and PC, may hold an 8-bit (1-byte) value. The Stack Pointer is used to indicate where the next value to be removed from the stack should be taken from. When you push a value onto the stack, the 8051 first increments the value of SP and then stores the value at the resulting memory location. When you pop a value off the stack, the 8051 returns the value from the memory location indicated by SP, and then decrements the value of SP.

This order of operation is important. When the 8051 is initialized SP will be initialized to 07h. If you immediately push a value onto the stack, the value will be stored in Internal RAM address 08h. This makes sense taking into account what was mentioned two paragraphs above: First the 8051 will increment the value of SP (from 07h to 08h) and then will store the pushed value at that memory address (08h).

TYPES OF MEMORY

The 8051 has three very general types of memory. To effectively program the 8051 it is necessary to have a basic understanding of these memory types. The memory types are illustrated in the following graphic. They are: On-Chip Memory, External Code Memory, and External RAM.

On-Chip Memory refers to any memory (Code, RAM, or other) that physically exists on the microcontroller itself. On-chip memory can be of several types, but we'll get into that shortly.

External Code Memory is code (or program) memory that resides off-chip. This is often in the form of an external EPROM.

External RAM is RAM memory that resides off-chip. This is often in the form of standard static RAM or flash RAM.

24

ADDRESSING MODES
An "addressing mode" refers to how you are addressing a given memory location. In summary, the addressing modes are as follows, with an example of each:

IMMEDIATE ADDRESSING

Immediate addressing is so-named because the value to be stored in memory immediately follows the operation code in memory. That is to say, the instruction itself dictates what value will be stored in memory. For example, the instruction: MOV A,#20h This instruction uses Immediate Addressing because the Accumulator will be loaded with the value that immediately follows; in this case 20 (hexidecimal).Immediate addressing is very fast since the value to be loaded is included in the instruction. However, since the value to be loaded is fixed at compile-time it is not very flexible.

DIRECT ADDRESSING Direct addressing is so-named because the value to be stored in memory is obtained by directly retrieving it from another memory location. For example: MOV A,30h This instruction will read the data out of Internal RAM address 30 (hexidecimal) and store it in the Accumulator. Direct addressing is generally fast since, although the value to be loaded isnt included in the instruction, it is quickly accessable since it is stored in the 8051s Internal RAM. It is also much more flexible than Immediate Addressing since the value to be loaded is whatever is found at the given address--which may be variable.

Also, it is important to note that when using direct addressing any instruction which refers to an address between 00h and 7Fh is referring to Internal Memory. Any instruction which refers to an address between 80h and FFh is referring to the SFR control registers that control the 8051 microcontroller itself.

REGISTER ADDRESSING

The register banks, containing registers R0 through R7, can be accessed by certain instructions which carry a 3-bit register specification within the opcode of the instruction. 25

Instructions that access the registers this way are code efficient, since this mode eliminates an address byte. When the instruction is executed, one of the eight registers in the selected bank is accessed. One of four banks is selected at execution time by the two bank select bits in the PSW.

REGISTER INDIRECT ADDRESSING

Indirect addressing is a very powerful addressing mode which in many cases provides an exceptional level of flexibility. Indirect addressing is also the only way to access the extra 128 bytes of Internal RAM found on an 8052. Indirect addressing appears as follows: MOV A,@R0 This instruction causes the 8051 to analyze the value of the R0 register. The 8051 will then load the accumulator with the value from Internal RAM which is found at the address indicated by R0.

INDEXED ADDRESSING Used in accessing data elements of look up table entries located in the program ROM space of 8051 eg. MOVC A@A+DPTR

TIMERS

The 8051 comes equipped with two timers, both of which may be controlled, set, read, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Counting the events themselves, or 3) Generating baud rates for the serial port. As mentioned before, the 8051 has two timers which each function essentially the same way. One timer is TIMER0 and the other is TIMER1. The two timers share two SFRs (TMOD and TCON) which control the timers, and each timer also has two SFRs dedicated solely to itself (TH0/TL0 and TH1/TL1).

26

Fig:6.2

13-BIT TIME MODE (MODE 0)

Timer mode "0" is a 13-bit timer. This is a relic that was kept around in the 8051 to maintain compatability with its predecesor, the 8048. Generally the 13-bit timer mode is not used in new development.When the timer is in 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means, in essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192 machine cycles later.

16-BIT TIME MODE (MODE 1)

Timer mode "1" is a 16-bit timer. This is a very commonly used mode. It functions just like 13-bit mode except that all 16 bits are used. TLx is incremented from 0 to 255. When TLx is incremented from 255, it resets to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer, the timer may contain up to 65536 distinct values. If you set a 16-bit timer to 0, it will overflow back to 0 after 65,536 machine cycles.

8-BIT TIME MODE (MODE 2)

Timer mode "2" is an 8-bit auto-reload mode. What is that, you may ask? Simple. When a timer is in mode 2, THx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counting up. When TLx reaches 255 and is subsequently incremented, instead of resetting to 0 (as in the case of modes 0 and 1), it will be reset to the value stored in THx. For example, lets say TH0 holds the value FDh and TL0 holds the value FEh. If we were to watch the values of TH0 and TL0 for a few machine cycles this is what wed see:As you can see, the value of TH0 never changed. In fact, when you use mode 2 you almost always set THx to a known value and TLx is the SFR that is constantly incremented. 27

SPLIT TIMER MODE (MODE 3)

Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and overflow back to 0. All the bits that are related to Timer 1 will now be tied to TH0. While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real timer 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what.

INTERRUPTS
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, 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 8051 may be configured so that when any of these events occur the main program is temporarily suspended and control passed to a special section of code which presumably would execute some function related to the event that occured. Once complete, control would be returned to the original program. The main program never even knows it was interrupted.

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 overflown, whether we had received another character via the serial port, or if some external event had occured. 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. INTERFACING Interfacing the Keyboard to the 8051

Keyboards and LCDs are the most widely used input/output devices of the 8051, and a basic understanding of them is essential. In this section, we first discuss keyboard fundamentals, along with key press and key detection mechanisms, Then we show how a keyboard is interfaced to an 8051.

28

At the lowest level, keyboards are organized in a matrix of rows and columns. The CPU accesses both rows and column through ports; therefore, with two 8-bit ports, an 8*8 matrix of keys can be connected to a microprocessor. When a key pressed, a row and column make a connect; otherwise, there is no connection between row and column. In IBM PC keyboards, a single microcontroller (consisting of microprocessor, RAM and EPROM, and several ports all on a single chip) takes care of software and hardware interfacing of keyboard. In such systems it is the function of programs stored in the EPROM of microcontroller to scan the keys continuously, identify which one has been activated, and present it to the motherboard. In this section we look at the mechanism by which the 8051 scans and identifies the key.

Scanning and identifying the key

As above shows a 4*4 matrix connected to two ports. The rows are connected to an output port and the columns are connected to an input port. If no key has been pressed, reading the input port will yield 1s for all columns since they are all connected to high (Vcc) If all the rows are grounded and a key is pressed, one of the columns will have 0 since the key pressed provides the path to ground. It is the function of the microcontroller to scan the keyboard continuously to detect and identify the key pressed. How it is done is explained next.

Fig:6.3

29

Grounding rows and reading columns

To detect a pressed key, the microcontroller grounds all rows by providing 0 to the output latch, and then it reads the columns. If the data read from the columns is D3-D0=1111, no key has been pressed and the process continues until a key press is detected. However, if one of the column bits has a zero, this means that a key press has occurred. For example, if D3-D0=1101, this means that a key in the D1 column has been pressed. After a key press is detected, the microcontroller will go through the process of identifying the key. Starting with the top row, the microcontroller grounds it by providing a low to row D0 only; then it reads the columns. If the data read is all1s, no key in that row is activated and the process is moved to the next row. It grounds the next row, reads the columns, and checks for any zero. This process continues until the row is identified. After identification of the row in which the key has been pressed, the next task is to find out which column the pressed key belongs to. This should be easy since the microcontroller knows at any time which row and column are being accessed.

Assembly language program for detection and identification of key activation is given below. In this program, it is assumed that P1 and P2 are initialized as output and input, respectively. Program goes through the following four major stages:

Keypad Interfacing

;Keyboard subroutine. This program sends the ASCII code ;for pressed key to P0.1 ;P1.0-P1.3 connected to rows P2.0-P2.3 connected to columns MOV P2,#0FFH K1: MOV P1,#0 MOV A,P2 ANL A,00001111B ;make P2 an input port ;ground all rows at once ;read all col. (ensure all keys open) ;masked unused bits

CJNE A,#00001111B,K1 ;check til all keys released K2: ACALL DELAY MOV A,P2 ;call 20 msec delay ;see if any key is pressed ;mask unused bits

ANL A,#00001111B

CJNE A,#00001111B,OVER ;key pressed, await closure SJMP K2 ;check il key pressed ;wait 20 msec debounce time

OVER: ACALL DELAY MOV A,P2

;check key closure ;mask unused bits 30

ANL A,#00001111B

CJNE A,#00001111B,OVER1;key pressed, find row SJMP K2 ;if none, keep polling ;ground row 0

OVER1: MOV P1,#11111110B MOV A,P2

;read all columns ;mask unused bits

ANL A,#00001111B

CJNE A,#00001111B,ROW_0;key row 0, find the col. MOV P1,#11111101B MOV A,P2 ;ground row 1

;read all columns ;mask unused bits

ANL A,#00001111B

CJNE A,#00001111B,ROW_1;keyrow 1, find the col. MOV P1,#11111011B MOV A,P2 ;ground row 2

;read all columns ;mask unused bits

ANL A,#00001111B

CJNE A,#00001111B,ROW_2;key row 2, find the col. MOV P1,#11110111B MOV A,P2 ;ground row 3

;read all columns ;mask unused bits

ANL A,#00001111B

CJNE A,#00001111B,ROW_3;keyrow 3, find the col. LJMP K2 ;if none, false input, repeat ;set DPTR=start of row 0

ROW_0: MOV DPTR,#KCODE0 SJMP FIND

;find col. key belongs to ;set DPTR=start of row 1

ROW_1: MOV DPTR,#KCODE1 SJMP FIND

;find col. key belongs to ;set DPTR=start of row 2

ROW_2: MOV DPTR,#KCODE2 SJMP FIND

;find col. key belongs to ;set DPTR=start of row 3

ROW_3: MOV DPTR,#KCODE3 FIND: RRC A JNC MATCH INC DPTR SJMP FIND MATCH: CLR A MOVC A,@A+DPTR MOV P0,A LJMP K1

;see if any CY bit low ;if zero, get the ASCII code ;point to next col. address ;keep searching ;set A=0 (match is found) ;get ASCII code from table

;display pressed key

;ASCII LOOK-UP TABLE FOR EACH ROW 31

ORG

300H '0','1','2','3' '4','5','6','7' '8','9','A','B' 'C','D','E','F' ;ROW 0 ;ROW 1 ;ROW 2 ;ROW 3

KCODE0: DB KCODE1: DB KCODE2: DB KCODE3: DB

END

32

CHAPTER 7

Getting The Embedded Software Into The Target System


The locator will build a file that describes the image of the target softaware. Let us see the issue of getting that file into the target system.

PROM Programmers

The classical way to get the software from the locator file into the target system is to create a RAM or PROM . Creating ROM is appropriate only when software development has been completed,since the too long cost to build ROMs is quite high.

Putting the program into a PROM requires a device called a PROM programmer. This is appropriate ifvolumes are not large enough to justify using a ROM, if plan to make changes to the software, or while we are debugging . If we plan to use PROMs and a PROM programmer for debugging purposes,it is usefulto build the version of the taaget system in which the PROM is placed in a socket on the target system rather than being soldered directly into the circuit. Then when we find a bug, we can remove the PROM containing the software with the bug from the target system and put it into the eraser or into the waste baket ,program a new PROM with software that has the bug fixed, and put that PROm into the socket. pin Well in socket to receive chip Contact switch to receive chip

Internal connection between contact in well& targetboard

Socket soldered to targetboard

Target board

Fig:7.1

33

Schematic view of socket


ROM emulator

Rom emulator is a device that replaces the ROM in the target system. From the point of view of the rest of the hardware in the target system, the emulator looks just like a ROM. However, the ROM emulator contains a large box of electronics and a serial port or a network connection through which it can be connected to our host. Software running on host send files created by the locator to the ROM emulator , which will act like a ROM that has been programmed with the software we have written.

ROM emulator

Serial network connections connects ROM emulator to host Ribbon cable attaches probe to ROM emulator

Probe from ROM emulator plugs into the memory chip socket

Fig:-7.2

34

CHAPTER 8

Future Trends In Embedded System RTOS


There is a flood of trends rushing through the embedded market today, many influencing the RTOS requirements in conflicting ways. It is hard to envision that five years from now RTOS products will bear much resemblance to what is supplied today. Some of these trends are application driven while others are device driven, and it is important to understand the influences these trends will have.

Application Specific:

In several markets, the end users have banded together to issue specific requirements for RTOSs to be used in their future products. They have purposely chosen to drop their proprietary behaviors of the past in order to get the benefits of multiple suppliers and interoperability of software. In this manner, only the needed software is linked into the application, preventing additional overhead and allowing for an extremely efficient kernel implementation.

System On A Chip (SOC):

As mentioned earlier, SOCs are beginning to appear throughout the embedded market, in at least three different ways. First, the semiconductor suppliers are providing developers the ability to pick and choose from a combination of industry standard functions integrated around a 32-bit core processor. These functions may include memory, IO drivers, a bus interface, network protocol support, or algorithms for special functions, such as an MPEG decoder. Second, end product manufacturers are integrating custom ASICs with common 32-bit core processors to provide complete solutions. Some recent examples include cable modems and ATM switches. And third, startups are emerging that will provide custom design services, complete with optimized RTOS, compiler, and debuggers.

SOC will be particularly well suited for a whole range of consumer electronics and wireless communications devices where size, cost, and low power requirements are crucial. It will also drive cost reductions in networking and telecom equipment, where more functionality can be added at lower costs. A subset of this SOC trend is the emergence of multi-core devices on single silicon. The most common to date has been the combination of standard microprocessors and Digital Signal Processors (DSPs). In some cases, the DSPs are dedicated function processors, but emerging trends have the DSP as a full programmable device.

35

Automatic Code Generation:

Probably the most radical notion is the idea that application code can be generated automatically from graphical diagrams depicting the logic flow for the end product. To a limited extent, this has already been

modeling and code generation. In the case of MATRIX, flight ready code for the international space station has been used for some time now, and the technology is being extended into the more restrictive automotive market. If these tools were to become reality, the whole notion of commercial RTOS and development tools will be upset, as the developer will only interact with the graphical tool, and will be totally isolated from the resulting software implementation.

36

CONCLUSION:

This seminar helped in understanding the following concepts.

1. Embedded systems application development. 2. The components of embedded systems.

3. The design issues. 4. The applications in which embedded systems are used. 5. RTOS and its features. 6. How to carry out effective presentation.

APPENDIX A
REFERENCES AND BIBILIOGRAPHY:
1. THE 8051 MICROCONTROLLER AND EMBEDDED SYSTEM BY MUHAMMAD ALI MAZIDI, JANICE ALI MAZIDI, ROLIN D. MCKINLEY 2. 3. 4. 5. 6. WWW.EN.WIKIPEDIA.COM WWW.EMBEDDED .COM WWW.8051PROJECTS.INFO WWW.EMBEDDEDRELATED.COM WWW.KEIL.COM

37

You might also like