Introduction to embeded system

87
INTRODUCTION TO EMBEDDED SYSTEM An Embedded System is a computer system designed to perform one or a few dedicated functions often with real-time computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. By contrast, a general-purpose computer, such as a personal computer (PC), is designed to be flexible and to meet a wide range of end-user needs. Embedded systems control many devices in common use today. Embedded Systems are controlled by one or more main processing cores that are typically either microcontrollers or digital signal processors (DSP).The key characteristic, however, is being dedicated to handle a particular task, which may require very powerful processors. For example, air traffic control systems may usefully be viewed as embedded, even though they involve mainframe computers and dedicated regional and national networks between airports and radar sites. (Each radar probably includes one or more embedded systems of its own.). Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Some embedded systems are mass-produced, benefiting from economies of scale. 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. In general, "embedded system" is not a strictly definable term, as most systems have some element of extensibility or programmability. For example, handheld computers share some elements with embedded systems such as the operating systems and microprocessors which power them, but they allow different applications to be loaded and peripherals to be connected. Moreover, even systems which don't expose programmability as a primary feature generally need to support software updates. On a continuum from "general purpose" to "embedded", large application systems will have

description

contains knowledge about architecture of microcontroller

Transcript of Introduction to embeded system

Page 1: Introduction to embeded system

INTRODUCTION TO EMBEDDED SYSTEM

An Embedded System is a computer system designed to perform one or a few dedicated functions often with real-time computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. By contrast, a general-purpose computer, such as a personal computer (PC), is designed to be flexible and to meet a wide range of end-user needs. Embedded systems control many devices in common use today. Embedded Systems are controlled by one or more main processing cores that are typically either microcontrollers or digital signal processors (DSP).The key characteristic, however, is being dedicated to handle a particular task, which may require very powerful processors. For example, air traffic control systems may usefully be viewed as embedded, even though they involve mainframe computers and dedicated regional and national networks between airports and radar sites. (Each radar probably includes one or more embedded systems of its own.). Since the embedded system is dedicated to specific tasks, design engineers can optimize it to reduce the size and cost of the product and increase the reliability and performance. Some embedded systems are mass-produced, benefiting from economies of scale. 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. In general, "embedded system" is not a strictly definable term, as most systems have some element of extensibility or programmability. For example, handheld computers share some elements with embedded systems such as the operating systems and microprocessors which power them, but they allow different applications to be loaded and peripherals to be connected. Moreover, even systems which don't expose programmability as a primary feature generally need to support software updates. On a continuum from "general purpose" to "embedded", large application systems will have subcomponents at most points even if the system as a whole is "designed to perform one or a few dedicated functions", and is thus appropriate to call "embedded".

Page 2: Introduction to embeded system

Variety of embedded systems

PC Engines' ALIX.1C Mini-ITX embedded board with an x86 AMD Geode LX 800 together with Compact Flash, mini PCI and PCI slots, 44-pin IDE interface, audio, USB and 256 MB RAM

An embedded Router Board 112 with U.FL-RSMA pigtail and R52 mini PCI Wi-Fi card widely used by wireless Internet service providers (WISPs) in the Czech Republic.Embedded systems span all aspects of modern life and there are many examples of their use.Telecommunications systems employ numerous embedded systems from telephone switches for the network to mobile phones at the end-user. Computer networking uses dedicated routers and network bridges to route data.Consumer electronics include personal digital assistants (PDAs), mp3 players, mobile phones, videogame consoles, digital cameras, DVD players, GPS receivers, and printers. Many household appliances, such as microwave ovens, washing machines and dishwashers, are including embedded systems to provide flexibility, efficiency and features. Advanced HVAC systems use networked thermostats to more accurately and efficiently control temperature that can change by time of day and season. Home automation uses wired- and wireless-networking that can be used to control lights, climate, security, audio/visual, surveillance, etc., all of which use embedded devices for sensing and controlling. Transportation systems from flight to automobiles increasingly use embedded systems. New airplanes contain advanced avionics such as inertial guidance systems and GPS receivers that also have considerable safety requirements. Various electric motors —brushless DC motors, induction motors and DC motors — are using electric/electronic motor controllers. Automobiles, electric vehicles, and hybrid

Page 3: Introduction to embeded system

vehicles are increasingly using embedded systems to maximize efficiency and reduce pollution. Other automotive safety systems include anti-lock braking system (ABS), Electronic Stability Control (ESC/ESP), traction control (TCS) and automatic four-wheel drive.Medical equipment is continuing to advance with more embedded systems for vital signs monitoring, electronic stethoscopes for amplifying sounds, and various medical imaging (PET, SPECT, CT, MRI) for non-invasive internal inspections.In addition to commonly described embedded systems based on small computers, a new class of miniature wireless devices called motes is quickly gaining popularity as the field of wireless sensor networking rises. Wireless sensor networking, WSN, makes use of miniaturization made possible by advanced IC design to couple full wireless subsystems to sophisticated sensors, enabling people and companies to measure a myriad of things in the physical world and act on this information through IT monitoring and control systems. These motes are completely self contained, and will typically run off a battery source for many years before the batteries need to be changed or charged.

History

In the earliest years of computers in the 1940–50s, computers were sometimes dedicated to a single task, but were far too large and expensive for most kinds of tasks performed by embedded computers of today. Over time however, the concept of programmable controllers evolved from traditional electromechanical sequencers, via solid state devices, to the use of computer technology.One of the first recognizably modern embedded systems was the Apollo Guidance Computer, developed by Char les Stark Draper at the MIT Instrumentation Laboratory. At the project's inception, the Apollo guidance computer was considered the riskiest item in the Apollo project as it employed the then newly developed monolithic integrated circuits to reduce the size and weight. An early mass-produced embedded system was the Automatics D-17 guidance computer for the Minuteman missile, released in 1961. It was built from transistor logic and had 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 was the first high-volume use of integrated circuits. This program alone reduced prices on quad nand gate ICs from $1000/each to $3/each [citation needed], permitting their use in commercial products.Since these early applications in the 1969s, embedded systems have come down in price and there has been a dramatic rise in processing power and functionality. The first microprocessor for example, the Intel 4004, was designed for calculators and other small systems but still required many external memory and support chips. In 1978 National Engineering Manufacturers Association released a "standard" for programmable microcontrollers, including almost any computer-based controllers, such as single board computers, numerical, and event-based controllers.As the cost of microprocessors and microcontrollers fell it became feasible to replace expensive knob-based analog components such as potentiometers and variable capacitors with up/down buttons or knobs read out by a microprocessor even in some consumer products. By the mid-1980s, most of the common previously external system components had been integrated into the same chip as the processor and this modern form of the microcontroller allowed an even more widespread use, which by the end of the decade were the norm rather than the exception for almost all electronics devices.The integration of microcontrollers has further increased the applications for which embedded systems are used into areas where traditionally a computer would not have

Page 4: Introduction to embeded system

been considered. A general purpose and comparatively low-cost microcontroller may often be programmed to fulfill the same role as a large number of separate components. Although in this context an embedded system is usually more complex than a traditional solution, most of the complexity is contained within the microcontroller itself. Very few additional components may be needed and most of the design effort is in the software. The intangible nature of software makes it much easier to prototype and test new revisions compared with the design and construction of a new circuit not using an embedded processor.

Characteristics

Gumstix Overo COM, a tiny, OMAP-based embedded computer-on-module with Wi-fi and Bluetooth.

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 reasons such as safety and usability; others may have low or no performance requirements, allowing the system hardware to be simplified to reduce costs.

1. Embedded systems are not always standalone devices. Many embedded systems consist of small, computerized parts within a larger device that serves a more general purpose. For example, the Gibson Robot Guitar features an embedded system for tuning the strings, but the overall purpose of the Robot Guitar is, of course, to play music. Similarly, an embedded system in an automobile provides a specific function as a subsystem of the car itself.

2. The program instructions written for embedded systems are referred to as firmware, and are stored in read-only memory or Flash memory chips. They run with limited computer hardware resources: little memory, small or non-existent keyboard and/or screen.

User interface

Embedded system text user interface using MicroVGAEmbedded systems range from no user interface at all — dedicated only to one task — to complex graphical user interfaces that resemble modern computer desktop operating systems. Simple embedded devices use buttons, LEDs, graphic or character LCDs (for example popular HD44780 LCD) with a simple menu system.

Page 5: Introduction to embeded system

A more sophisticated devices use graphical screen with touch sensing or screen-edge buttons provide flexibility while minimizing space used: the meaning of the buttons can change with the screen, and selection involves the natural behavior of pointing at what's desired. Handheld systems often have a screen with a "joystick button" for a pointing device.Some systems provide user interface remotely with the help of serial (e.g. RS-232, USB, I²C, etc.) or network (e.g. Ethernet) connection. In spite of installed client software and cables are needed this approach usually gives a lot of advantages: extends the capabilities of embedded system, avoids the cost of a display, simplifies BSP, allows to build rich user interface on PC.One of the well established models in this direction is the combination of  embedded web server running on embedded device like IP camera or network routers and user interface shown in web browser of PC connected with Ethernet or wi-fi to embedded device.

Processors in embedded systems

Embedded processors can be broken into two broad categories: ordinary 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 architectures, RISC as well as non-RISC and VLIW; word lengths vary from 4-bit to 64-bits and beyond (mainly in DSP processors) although the most typical remain 8/16-bit. Most architecture come in a large number of different variants and shapes, many of which are also manufactured by several different companies.A long but still not exhaustive list of common architectures are: 65816, 65C02, 68HC08, 68HC11, 68k, 8051, ARM, AVR, AVR32,Blackfin, C167, Coldfire, COP8, Cortus APS3, eZ8, eZ80, FR-V, H8, HT48, M16C,  M32C, MIPS, MSP430, PIC, PowerPC, R8C,SHARC, SPARC, ST6, SuperH, TLCS-47, TLCS-870, TLCS-900, Tricore,  V850, x86, XE8000, Z80, ASAP etc.

Ready made computer boards

PC/104 and PC/104+ are examples of standards for ready made computer boards intended for small, low-volume embedded and ruggedized systems, mostly x86-based. These often use DOS, Linux, NetBSD, or an embedded real-time operating system such as MicroC/OS-II, QNX or VxWorks. Sometimes these boards use non-x86 processors.In certain applications, where small size or power efficiency are not primary concerns, the components used may be compatible with those used in general purpose x86 personal computers. Boards such as the VIA EPIA range help to bridge the gap by being PC-compatible but highly integrated, physically smaller or have other attributes making them attractive to embedded engineers. The advantage of this approach is that low-cost commodity components may be used along with the same software development tools used for general software development. Systems built in this way are still regarded as embedded since they are integrated into larger devices and fulfill a single role. Examples of devices that may adopt this approach are ATMs and arcade machines, which contain code specific to the application.However, most ready-made embedded systems boards are not PC-centered and do not use the ISA or PCI busses. When a System-on-a-chip processor is involved, there may be

Page 6: Introduction to embeded system

little benefit to having a standardized bus connecting discrete components, and the environment for both hardware and software tools may be very different.One common design style uses a small system module, perhaps the size of a business card, holding high density BGA chips such as an ARM-based System-on-a-chip processor and peripherals, external flash memory for storage, and DRAM for runtime memory. The module vendor will usually provide boot software and make sure there is a selection of operating systems, usually including Linux and some real time choices. These modules can be manufactured in high volume, by organizations familiar with their specialized testing issues, and combined with much lower volume custom main boards with application-specific external peripherals. Gumstix product lines are a Linux-centric example of this model.

ASIC and FPGA solutions

A common configuration for very-high-volume embedded systems is the system on a chip (SoC) which contains a complete system consisting of multiple processors, multipliers, caches and interfaces on a single chip. SoCs can be implemented as an application-specific integrated circuit (ASIC) or using a field-programmable gate array (FPGA).

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: I2C, SPI, SSC and ESSI

(Enhanced Synchronous Serial Interface) Universal Serial Bus (USB) Multi Media Cards (SD Cards, Compact Flash etc.) Networks: Ethernet, Controller Area Network, LonWorks, etc. Timers: PLL(s), Capture/Compare and Time Processing Units Discrete IO: General Purpose Input/Output (GPIO) Analog to Digital/Digital to Analog (ADC/DAC) Debugging: JTAG, ISP, ICSP, BDM Port, BITP DP9 port ...

Tools

As for other software, embedded system designers use compilers, assemblers, and debuggers to develop embedded system software. However, they may also use some more specific tools:

In circuit debuggers or emulators (see next section). Utilities to add a checksum or CRC to a program, so the embedded system can

check if the program is valid. For systems using digital signal processing, developers may use a math

workbench such as Scilab / Scicos, MATLAB / Simulink, EICASLAB, MathCAD Mathematica, or FlowStone DSP to simulate the mathematics. They might also use libraries for both the host and target which eliminates developing DSP routines as done in DSP nano RTOS and Unison Operating System.

Page 7: Introduction to embeded system

Custom compilers and linkers may be used to improve optimization for the particular hardware.

An embedded system may have its own special language or design tool, or add enhancements to an existing language such as Forth or Basic.

Another alternative is to add a real-time operating system or embedded operating system, which may have DSP capabilities like DSP nano RTOS.

Software tools can come from several sources: Software companies that specialize in the embedded market Ported from the GNU software development tools Sometimes, development tools for a personal computer can be used if the

embedded processor is a close relative to a common PC processorAs the complexity of embedded systems grows, higher level tools and operating systems are migrating into machinery where it makes sense. For example, cell phones, personal digital assistants and other consumer computers often need significant software that is purchased or provided by a person other than the manufacturer of the electronics. In these systems, an open programming environment such as Linux, NetBSD, OSGi or Embedded Java is required so that the third-party software provider can sell to a large market.

Debugging

Embedded debugging may be performed at different levels, depending on the facilities available. From simplest to most sophisticate they can be roughly grouped into the following areas:

Interactive resident debugging, using the simple shell provided by the embedded operating system (e.g. Forth and Basic)

External debugging using logging or serial port output to trace operation using either a monitor in flash or using a debug server like the Remedy Debugger which even works for heterogeneous multicore systems.

An in-circuit debugger (ICD), a hardware device that connects to the microprocessor via a JTAG or Nexus interface. This allows the operation of the microprocessor to be controlled externally, but is typically restricted to specific debugging capabilities in the processor.

An in-circuit emulator replaces the microprocessor with a simulated equivalent, providing full control over all aspects of the microprocessor.

A complete emulator provides a simulation of all aspects of the hardware, allowing all of it to be controlled and modified, and allowing debugging on a normal PC.

Unless restricted to external debugging, the programmer can typically load and run software through the tools, view the code running in the processor, and start or stop its operation. The view of the code may be as assembly code or source-code.Because an embedded system is often composed of a wide variety of elements, the debugging strategy may vary. For instance, debugging a software- (and microprocessor-) centric embedded system is different from debugging an embedded system where most of the processing is performed by peripherals (DSP, FPGA, co-processor). An increasing number of embedded systems today use more than one single processor core. A common problem with multi-core development is the proper synchronization of software execution. In such a case, the embedded system design may wish to check the data traffic on the busses between the processor cores, which requires very low-level debugging, at signal/bus level, with a logic analyzer, for instance.

Page 8: Introduction to embeded system

Reliability

Embedded systems often reside in machines that are expected to run continuously for years without errors, and in some cases recover by themselves if an error occurs. Therefore the software is usually developed and tested more carefully than that for personal computers, and unreliable mechanical moving parts such as disk drives, switches or buttons are avoided.Specific reliability issues may include:

1. The system cannot safely be shut down for repair, or it is too inaccessible to repair. Examples include space systems, undersea cables, navigational beacons, bore-hole systems, and automobiles.

2. The system must be kept running for safety reasons. "Limp modes" are less tolerable. Often backups are selected by an operator. Examples include aircraft navigation, reactor control systems, safety-critical chemical factory controls, train signals, engines on single-engine aircraft.

3. The system will lose large amounts of money when shut down: Telephone switches, factory controls, bridge and elevator controls, funds transfer and market making, automated sales and service.

A variety of techniques are used, sometimes in combination, to recover from errors—both software bugs such as memory leaks, and also soft errors in the hardware:

watchdog timer that resets the computer unless the software periodically notifies the watchdog

subsystems with redundant spares that can be switched over to software "limp modes" that provide partial function Designing with a Trusted Computing Base (TCB) architecture ensures a highly

secure & reliable system environment An Embedded Hypervisor is able to provide secure encapsulation for any

subsystem component, so that a compromised software component cannot interfere with other subsystems, or privileged-level system software. This encapsulation keeps faults from propagating from one subsystem to another, improving reliability. This may also allow a subsystem to be automatically shut down and restarted on fault detection.

Immunity Aware Programming

High vs low volume

For high volume systems such as portable music players or mobile phones, minimizing cost is usually the primary design consideration. Engineers typically select hardware that is just “good enough” to implement the necessary functions.For low-volume or prototype embedded systems, general purpose computers may be adapted by limiting the programs or by replacing the operating system with a real-time operating system.

Embedded software architectures

There are several different types of software architecture in common use.

Simple control loop

Page 9: Introduction to embeded system

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. An interrupt could be generated for example by a timer in a predefined frequency, or by a serial port controller receiving a byte.These kinds of systems are used if event handlers need low latency and the event handlers are short and simple.Usually these kinds of systems run a simple task in a main loop also, but this task is not very sensitive to unexpected delays.Sometimes the interrupt handler will add longer tasks to a queue structure. Later, after the interrupt handler has finished, these tasks are executed by the main loop. This method brings the system close to a multitasking kernel with discrete processes.

Cooperative multitasking

A no 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. When a task is idle, it calls an idle routine, usually called “pause”, “wait”, “yield”, “nop” (stands for no operation), etc.The advantages and disadvantages are very similar to the control loop, except that adding new software is easier, by simply writing a new task, or adding to the queue-interpreter.

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.As any code can potentially damage the data of another task (except in larger systems using an MMU) programs must be carefully designed and tested, and access to shared data must be controlled by some synchronization strategy, such as queues, semaphores or a non-blocking synchronization scheme.Because of these complexities, it is common for organizations to buy a real-time operating system, allowing the application programmers to concentrate on device functionality rather than operating system services, at least for large systems; smaller systems often cannot afford the overhead associated with a generic real time system, due to limitations regarding memory size, performance, and/or battery life.

Microkernels and exokernels

A microkernel is a logical step up from a real-time OS. The usual arrangement is that the operating system kernel allocates memory and switches the CPU to different threads of execution. User mode processes implement major functions such as file systems, network interfaces, etc.In general, microkernels succeed when the task switching and intertask communication is fast, and fail when they are slow.

Page 10: Introduction to embeded system

Exokernels communicate efficiently by normal subroutine calls. The hardware and all the software in the system are available to, and extensible by application programmers.Monolithic kernels

In this case, a relatively large kernel with sophisticated capabilities is adapted to suit an embedded environment. This gives programmers an environment similar to a desktop operating system like Linux or Microsoft Windows, and is therefore very productive for development; on the downside, it requires considerably more hardware resources, is often more expensive, and because of the complexity of these kernels can be less predictable and reliable.Common examples of embedded monolithic kernels are Embedded Linux and Windows CE.Despite the increased cost in hardware, this type of embedded system is increasing in popularity, especially on the more powerful embedded devices such as Wireless Routers and GPS Navigation Systems. Here are some of the reasons:

Ports to common embedded chip sets are available. They permit re-use of publicly available code for Device Drivers, Web

Servers, Firewalls, and other code. Development systems can start out with broad feature-sets, and then the

distribution can be configured to exclude unneeded functionality, and save the expense of the memory that it would consume.

Many engineers believe that running application code in user mode is more reliable, easier to debug and that therefore the development process is easier and the code more portable.

Many embedded systems lack the tight real time requirements of a control system. Although a system such as Embedded Linux may be fast enough in order to respond to many other applications.

Features requiring faster response than can be guaranteed can often be placed in hardware.

Many RTOS systems have a per-unit cost. When used on a product that is or will become a commodity, that cost is significant.

Exotic custom operating systems

A small fraction of embedded systems require safe, timely, reliable or efficient behavior unobtainable with the one of the above architectures. In this case an organization builds a system to suit. In some cases, the system may be partitioned into a "mechanism controller" using special techniques, and a "display controller" with a conventional operating system. A communication system passes data between the two.

Additional software components

In addition to the core operating system, many embedded systems have additional upper-layer software components. These components consist of networking protocol stacks like CAN, TCP/IP, FTP, HTTP, and HTTPS, and also included storage capabilities like FAT and flash memory management systems. If the embedded devices has audio and video capabilities, then the appropriate drivers and codecs will be present in the system. In the case of the monolithic kernels, many of these software layers are included. In the RTOS category, the availability of the additional software components depends upon the commercial offering.

Page 11: Introduction to embeded system

Microcontroller

The die from an Intel 8742, an 8-bit microcontroller that includes a CPU running at 12 MHz, 128 bytes of RAM, 2048 bytes of EPROM, and I/O in the same chip.A microcontroller (sometimes abbreviated µC or uC) is a small computer on a single integrated containing a processor core, memory, and programmable input/output peripherals. Program memory in the form of NOR flash or OTP ROM is also often included on chip, as well as a typically small amount of RAM. Microcontrollers are designed for embedded, in contrast to the microprocessors used in personal computers or other general purpose applications.Microcontrollers are used in automatically controlled products and devices, such as automobile engine control systems, implantable medical devices, remote controls, office machines, appliances, power tools, and toys. By reducing the size and cost compared to a design that uses a separate microprocessor, memory, and input/output devices, microcontrollers make it economical to digitally control even more devices and processes. Mixed signal microcontrollers are common, integrating analog components needed to control non-digital electronic systems.Some microcontrollers may use four-bit words and operate at clock rate frequencies as low as 4 kHz, for low power consumption (mill watts or microwatts). They will generally have the ability to retain functionality while waiting for an event such as a button press or other interrupt; power consumption while sleeping (CPU clock and most peripherals off) may be just nanowatts, making many of them well suited for long lasting battery applications. Other microcontrollers may serve performance-critical roles, where they may need to act more like a digital signal processor (DSP), with higher clock speeds and power consumption.

Embedded design

A microcontroller can be considered a self-contained system with a processor, memory and peripherals and can be used as an embedded system. The majority of microcontrollers in use today are embedded in other machinery, such as automobiles, telephones, appliances, and peripherals for computer systems. These are called embedded systems. While some embedded systems are very sophisticated, many have minimal requirements for memory and program length, with no operating system, and low software complexity. Typical input and output devices include switches, relays, solenoids, LEDs, small or custom LCD displays, radio frequency

Page 12: Introduction to embeded system

devices, and sensors for data such as temperature, humidity, light level etc. Embedded systems usually have no keyboard, screen, disks, printers, or other recognizable I/O devices of a personal computer, and may lack human interaction devices of any kind.

Interrupts

Microcontrollers must provide real time (predictable, though not necessarily fast) response to events in the embedded system they are controlling. When certain events occur, an interrupt system can signal the processor to suspend processing the current instruction sequence and to begin an interrupt service routine (ISR, or "interrupt handler"). The ISR will perform any processing required based on the source of the interrupt before returning to the original instruction sequence. Possible interrupt sources are device dependent, and often include events such as an internal timer overflow, completing an analog to digital conversion, a logic level change on an input such as from a button being pressed, and data received on a communication link. Where power consumption is important as in battery operated devices, interrupts may also wake a microcontroller from a low power sleep state where the processor is halted until required to do something by a peripheral event.

Programs

Microcontroller programs must fit in the available on-chip program memory, since it would be costly to provide a system with external, expandable, memory. Compilers and assemblers are used to turn high-level language and assembler language codes into a compact machine code for storage in the microcontroller's memory. Depending on the device, the program memory may be permanent, read-only memory that can only be programmed at the factory, or program memory may be field-alterable flash or erasable read-only memory.

Other microcontroller features

Microcontrollers usually contain from several to dozens of general purpose input/output pins (GPIO). GPIO pins are software configurable to either an input or an output state. When GPIO pins are configured to an input state, they are often used to read sensors or external signals. Configured to the output state, GPIO pins can drive external devices such as LED's or motors.Many embedded systems need to read sensors that produce analog signals. This is the purpose of the analog-to-digital converter (ADC). Since processors are built to interpret and process digital data, i.e. 1s and 0s, they won't be able to do anything with the analog signals that may be sent to it by a device. So the analog to digital converter is used to convert the incoming data into a form that the processor can recognize. A less common feature on some microcontrollers is a digital-to-analog converter (DAC) that allows the processor to output analog signals or voltage levels.In addition to the converters, many embedded microprocessors include a variety of timers as well. One of the most common types of timers is the Programmable Interval Timer (PIT). A PIT just counts down from some value to zero. Once it reaches zero, it sends an interrupt to the processor indicating that it has finished counting. This is useful for devices such as thermostats, which periodically test the temperature around them to see if they need to turn the air conditioner on, the heater on, etc. Time Processing

Page 13: Introduction to embeded system

Unit (TPU) is a sophisticated timer. In addition to counting down, the TPU can detect input events, generate output events, and perform other useful operations.A dedicated Pulse Width Modulation (PWM) block makes it possible for the CPU to control power converters, resistive loads, motors, etc., without using lots of CPU resources in tight timer loops.Universal Asynchronous Receiver/Transmitter (UART) block makes it possible to receive and transmit data over a serial line with very little load on the CPU. Dedicated on-chip hardware also often includes capabilities to communicate with other devices (chips) in digital formats such as I2C and Serial Peripheral Interface (SPI).

Higher integration

In contrast to general-purpose CPUs, micro-controllers may not implement an external address or data bus as they integrate RAM and non-volatile memory on the same chip as the CPU. Using fewer pins, the chip can be placed in a much smaller, cheaper package.Integrating the memory and other peripherals on a single chip and testing them as a unit increases the cost of that chip, but often results in decreased net cost of the embedded system as a whole. Even if the cost of a CPU that has integrated peripherals is slightly more than the cost of a CPU and external peripherals, having fewer chips typically allows a smaller and cheaper circuit board, and reduces the labor required to assemble and test the circuit board.A micro-controller is a single integrated circuit, commonly with the following features:

central processing unit - ranging from small and simple 4-bit processors to complex 32- or 64-bit processors

discrete input and output bits, allowing control or detection of the logic state of an individual package pin

serial input/output such as serial ports (UARTs) other serial communications interfaces like I²C, Serial Peripheral

Interface and Controller Area Network for system interconnect peripherals such as timers, event counters, PWM generators, and watchdog volatile memory (RAM) for data storage ROM, EPROM, EEPROM or Flash memory for program and operating

parameter storage clock generator - often an oscillator for a quartz timing crystal, resonator or RC

circuit many include analog-to-digital converters in-circuit programming and debugging support

This integration drastically reduces the number of chips and the amount of wiring and circuit board space that would be needed to produce equivalent systems using separate chips. Furthermore, and on low pin count devices in particular, each pin may interface to several internal peripherals, with the pin function selected by software. This allows a part to be used in a wider variety of applications than if pins had dedicated functions. Micro-controllers have proved to be highly popular in embedded systems since their introduction in the 1970s.Some microcontrollers use Harvard architecture: separate memory buses for instructions and data, allowing accesses to take place concurrently. Where Harvard architecture is used, instruction words for the processor may be a different bit size than the length of internal memory and registers; for example: 12-bit instructions used with 8-bit data registers.

Page 14: Introduction to embeded system

The decision of which peripheral to integrate is often difficult. The microcontroller vendors often trade operating frequencies and system design flexibility against time-to-market requirements from their customers and overall lower system cost. Manufacturers have to balance the need to minimize the chip size against additional functionality.Microcontroller architectures vary widely. Some designs include general-purpose microprocessor cores, with one or more ROM, RAM, or I/O functions integrated onto the package. Other designs are purpose built for control applications. A micro-controller instruction set usually has many instructions intended for bit-wise operations to make control programs more compact. For example, a general purpose processor might require several instructions to test a bit in a register and branch if the bit is set, where a micro-controller could have a single instruction to provide that commonly-required function.Microcontrollers typically do not have a math coprocessor, so floating point arithmetic is performed by software.

Volumes

About 55% of all CPUs sold in the world are 8-bit microcontrollers and microprocessors. According to Semico, over four billion 8-bit microcontrollers were sold in 2006. A typical home in a developed country is likely to have only four general-purpose microprocessors but around three dozen microcontrollers. A typical mid-range automobile has as many as 30 or more microcontrollers. They can also be found in many electrical device such as washing machines, microwave ovens, and telephones.

A PIC 18F8720 microcontroller in an 80-pin TQFP package.Manufacturers have often produced special versions of their microcontrollers in order to help the hardware and software development of the target system. Originally these included EPROM versions that have a "window" on the top of the device through which program memory can be erased by ultraviolet light, ready for reprogramming after a programming ("burn") and test cycle. Since 1998, EPROM versions are rare and have been replaced by EEPROM and flash, which are easier to use (can be erased electronically) and cheaper to manufacture.Other versions may be available where the ROM is accessed as an external device rather than as internal memory, however these are becoming increasingly rare due to the widespread availability of cheap microcontroller programmers.The use of field-programmable devices on a microcontroller may allow field update of the firmware or permit late factory revisions to products that have been assembled but

Page 15: Introduction to embeded system

not yet shipped. Programmable memory also reduces the lead time required for deployment of a new product.

Programming environments

Microcontrollers were originally programmed only in assembly language, but various high-level programming languages are now also in common use to target microcontrollers. These languages are either designed specially for the purpose, or versions of general purpose languages such as the C programming language. Compilers for general purpose languages will typically have some restrictions as well as enhancements to better support the unique characteristics of microcontrollers. Some microcontrollers have environments to aid developing certain types of applications. Microcontroller vendors often make tools freely available to make it easier to adopt their hardware.Many microcontrollers are so quirky that they effectively require their own non-standard dialects of C, such as SDCC for the 8051, which prevent using standard tools (such as code libraries or static analysis tools) even for code unrelated to hardware features. Interpreters are often used to hide such low level quirks.Interpreter firmware is also available for some microcontrollers. For example, BASIC on the early microcontrollers Intel 8052 BASIC and FORTH on the Zilog Z8 as well as some modern devices. Typically these interpreters support interactive programming.Simulators are available for some microcontrollers, such as in Microchip's MPLAB environment. These allow a developer to analyze what the behavior of the microcontroller and their program should be if they were using the actual part. A simulator will show the internal processor state and also that of the outputs, as well as allowing input signals to be generated. While on the one hand most simulators will be limited from being unable to simulate much other hardware in a system, they can exercise conditions that may otherwise be hard to reproduce at will in the physical implementation, and can be the quickest way to debug and analyze problems..Types of microcontrollers

As of 2008 there are several dozen microcontroller architectures and vendors including: 68HC11 8051 ARM processors (from many vendors) using ARM7 or Cortex-M3 cores are

generally microcontrollers STMicroelectronics STM8S (8-bit), ST10 (16-bit) and STM32 (32-bit) Atmel AVR (8-bit), AVR32 (32-bit), and AT91SAM Freescale ColdFire (32-bit) and S08 (8-bit) Hitachi H8, Hitachi SuperH Hyperstone E1/E2 (32-bit, First full integration of RISC and DSP on one

processor core [1996]) MIPS (32-bit PIC32) NEC V850 PIC (8-bit PIC16, PIC18, 16-bit dsPIC33 / PIC24) PowerPC ISE PSoC (Programmable System-on-Chip) Rabbit 2000

Page 16: Introduction to embeded system

Texas Instruments Microcontrollers MSP430 (16-bit), C2000 (32-bit), and Stellaris (32-bit)

Toshiba TLCS-870 Zilog eZ8, eZ80

and many others, some of which are used in very narrow range of applications or are more like applications processors than microcontrollers. The microcontroller market is extremely fragmented, with numerous vendors, technologies, and markets. Note that many vendors sell (or have sold) multiple architectures.

Interrupt latency

In contrast to general-purpose computers, microcontrollers used in embedded systems often seek to optimize interrupt latency over instruction throughput. Issues include both reducing the latency, and making it be more predictable (to support real-time control).When an electronic device causes an interrupt, the intermediate results (registers) have to be saved before the software responsible for handling the interrupt can run. They must also be restored after that software is finished. If there are more registers, this saving and restoring process takes more time, increasing the latency. Ways to reduce such context/restore latency include having relatively few registers in their central processing units (undesirable because it slows down most non-interrupt processing substantially), or at least not having hardware save them all (hoping that the software doesn't then need to compensate by saving the rest "manually"). Another technique involves spending silicon gates on "shadow registers": one or more duplicate registers used only by the interrupt software, perhaps supporting a dedicated stack.Other factors affecting interrupt latency include:

Cycles needed to complete current CPU activities. To minimize those costs, microcontrollers tend to have short pipelines (often three instructions or less), small write buffers, and ensure that longer instructions are continuable or restartable. RISC design principles ensure that most instructions take the same number of cycles, helping avoid the need for most such continuation/restart logic.

The length of any critical section that needs to be interrupted. Entry to a critical section restricts concurrent data structure access. When a data structure must be accessed by an interrupt handler, the critical section must block that interrupt. Accordingly, interrupt latency is increased by however long that interrupt is blocked. When there are hard external constraints on system latency, developers often need tools to measure interrupt latencies and track down which critical sections cause slowdowns.

One common technique just blocks all interrupts for the duration of the critical section. This is easy to implement, but sometimes critical sections get uncomfortably long.

A more complex technique just blocks the interrupts that may trigger access to that data structure. This often based on interrupt priorities, which tend to not correspond well to the relevant system data structures. Accordingly, this technique is used mostly in very constrained environments.

Processors may have hardware support for some critical sections. Examples include supporting atomic access to bits or bytes within a word, or other atomic access primitives like the LDREX/STREX exclusive access primitives introduced in the ARMv6architecture.

Interrupt nesting. Some microcontrollers allow higher priority interrupts to interrupt lower priority ones. This allows software to manage latency by giving

Page 17: Introduction to embeded system

time-critical interrupts higher priority (and thus lower and more predictable latency) than less-critical ones.

Trigger rate. When interrupts occur back-to-back, microcontrollers may avoid an extra context save/restore cycle by a form of tail call optimization.

.History

The first single-chip microprocessor was the 4-bit Intel 4004 released in 1971. With the Intel 8008 and more capable microprocessors available over the next several years.These however all required external chip(s) to implement a working system, raising total system cost, and making it impossible to economically computerize appliances.The first computer system on a chip optimized for control applications - microcontroller was the Intel 8048 released in 1975, with both RAM and ROM on the same chip. This chip would find its way into over one billion PC keyboards, and other numerous applications. At this time Intels President, Luke J. Valenter, stated that the (Microcontroller) was one of the most successful in the companies history and expanded the division's budget over 25%.Most microcontrollers at this time had two variants. One had an erasable EEPROM program memory, which was significantly more expensive than the PROM variant which was only programmable once.In 1993, the introduction of EEPROM memory allowed microcontrollers (beginning with the Microchip PIC16x84)  to be electrically erased quickly without an expensive package as required for EPROM, allowing both rapid prototyping, and In System Programming.The same year, Atmel introduced the first microcontroller using Flash memory. Other companies rapidly followed suit, with both memory types.

Microcontroller embedded memory technology

Since the emergence of microcontrollers, many different memory technologies have been used. Almost all microcontrollers have at least two different kinds of memory, a non-volatile memory for storing firmware and a read-write memory for temporary data.

Data

From the earliest microcontrollers to today, six-transistor SRAM is almost always used as the read/write working memory, with a few more transistors per bit used in the register file. MRAM could potentially replace it as it is 4-10 times denser which would make it more cost effective.In addition to the SRAM, some microcontrollers also have internal EEPROM for data storage; and even ones that don't have any (or don't have enough) are often connected to external serial EEPROM chip (such as the BASIC Stamp) or external serial flash memory chip.A few recent microcontrollers beginning in 2003 have "self-programmable" flash memory.

Firmware

The earliest microcontrollers used hard-wired or mask ROM to store firmware. Later microcontrollers (such as the early versions of the Freescale 68HC11 and early PIC

Page 18: Introduction to embeded system

microcontrollers) had quartz windows that allowed ultraviolet light in to erase the EPROM.The Microchip PIC16C84, introduced in 1993, was the first microcontroller to use EEPROM to store firmware.

EMBEDDED SYSTEM DESIGN USING 8051 MICROCONROLLER

Page 19: Introduction to embeded system

INTRODUCTION TO 8051 MICROCONROLLER

The 8051 is an 8-bit microcontroller originally developed by Intel in the year 1980. it is the world’s most popular microcontroller core, made by many independent manufacturers(truly multi-sourced).A typical microcontroller contains:

CPU with Boolean processor 5 or 6 interupts: 2 are external Priority levels 3 16-bit timers/counters Programmable full-duplex serial port (baud rate provided by one of the timers) 32 I/O lines RAM ROM/EPROM in some models

The 8051 architecture is a tad bizarre, but then so are the architectures of most microcontrollers due to their specialization. One vexing problem with the 8051 is its very non-orthogonal instruction set-especially the restrictions on accessing the different address spaces. However, after some time programming the chip, you can get used to it –may be even appreciate it.One strong point of the 8051 is the way it handles interrupts. Vectoring to fixed 8-byte areas is convenient and efficient. Most interrupt routines are very short and generally can fit into the 8-byte area. Of course if your interrupt routine is longer, you can still jump to the appropriate routine from within the 8 byte interrupt region.The 8051 instruction set is optimized for the one-bit operations so often desired in real-world, real-time control applications. The Boolean processor provides direct support for bit manipulation. This leads to more efficient programs that need to deal with binary input and output conditions inherent in digital-control problems. Bit addressing can be used for test pin monitoring or program control flags.

8051 Flavors

The 8051 has the widest range of variants of any embedded controller on the market. The smallest device is the Atmel 89c1051, a 20 pin FLASH variant with 2 timers, UART, 20mA. The fastest parts are form Dallas, with performance close to 10 MIPS! The most powerful chip is the Siemens 80C517A, with 32 bit ALU, 2 UARTs, 2K RAM, PLCC84 package, 8x16 bit PWMs and other features.Among the major manufacturers are:AMD Enhanced 8051 partsAtmel FLASH and semi-custom partsDallas Battery backed, program download and faster variantsIntel 8051 through 80c51gb/80c51slMatra 80c154, low voltage static variantsOKI 80c154, mask partsPhillips 87c748 thru 89c588-more variants than anyone else

Page 20: Introduction to embeded system

Siemens 80c501 through 80c517a and SIECO coresSMC COM20051 with ARCNET token bus network engineSSI 80x52, 2xHDLC variant for MODEM use

16-bit 8051 parts

A joint project between Intel and Phillips Semiconductors has resulted in two new exciting products- 16 bit 8051! Due to a disagreement between the parties, they each went their separate ways. Intel developed the MCS-251, which was originally called the ZX. Phillips came out with the extended Architecture (XA) line.

Intel MCS-251

The intel MCS-251 is 100% binary and pin compatible with the 8051, but with a 5-15 timers boost in horsepower. This is achieved by a six fold gain in bus cycles, and further hardware improvements to avoid wasted bus cycles.Further performance gains are possible by recording critical sections to take advantage of the new features: powerful 8/16/32 bit instructions, flexible 8/16/32 registers and 16MB linear address space, 16-bit stack pointer, enhanced BIT manipulations and improved control instructions. In addition to extra 16/32 bit instructions, the 251 includes 40 registers with accumulator and index functions overplayed as 16x8, 16x16, 16x32.

Phillips 8051XA

By tossing compatibility out the window, Philips was able to develop a true 16 microcontroller while at the same time preserving the basic 8051 instruction set. The benefits of this break with tradition result in a chip that has dual 16MB address spaces, multitasking support with task protected memory segments, a separate SFR bus, fast context switching and optimized code efficiency.Other features include:

Hardware divide and multiply (over 100 times faster than an 8051) 32 vectored interrupts 16 hardware exceptions 16 trap instructions

Figure 1.1 shows a functional block of the internal operation of an 8051microcontroller. The internal components of the chip are shown within the broken line box.

Page 21: Introduction to embeded system

Figure: 8051 functional block diagram.

Figure 1.2 shows the external code memory and data memory connected to the 8051chip.

Figure: 8051 chip with external memory

Page 22: Introduction to embeded system

MEMORY AND REGISTER ORGANISATION

The 8051 has a separate memory space for code (programs) and data. We will referhere to on-chip memory and external memory as shown in figure 1.5. In an actualimplementation the external memory may, in fact, be contained within the microcomputer chip. However, we will use the definitions of internal and externalmemory to be consistent with 8051 instructions which operate on memory. Note, theseparation of the code and data memory in the 8051 architecture is a little unusual.The separated memory architecture is referred to as Harvard architecture whereasVon Neumann architecture defines a system where code and data can share commonmemory.

Figure: 8051 Memory representation

External Code Memory

The executable program code is stored in this code memory. The code memory size islimited to 64KBytes (in a standard 8051). The code memory is read-only in normaloperation and is programmed under special conditions e.g. it is a PROM or a FlashRAM type of memory.

External RAM Data Memory

This is read-write memory and is available for storage of data. Up to 64KBytes ofexternal RAM data memory is supported (in a standard 8051).

Internal Memory

The 8051’s on-chip memory consists of 256 memory bytes organised as follows:

First 128 bytes: 00h to 1Fh Register Banks20h to 2Fh Bit Addressable RAM30 to 7Fh General Purpose RAM

Next 128 bytes: 80h to FFh Special Function RegistersThe first 128 bytes of internal memory is organized as shown in figure 1.6, and isreferred to as Internal RAM, or IRAM.

Page 23: Introduction to embeded system

Figure 1.6 Organisation of Internal RAM (IRAM) memory

Register Banks: 00h to 1Fh

The 8051 uses 8 general-purpose registers R0 through R7 (R0, R1, R2, R3, R4, R5,R6, and R7). These registers are used in instructions such as:

ADD A, R2 ; adds the value contained in R2 to the accumulator

Note since R2 happens to be memory location 02h in the Internal RAM the followinginstruction has the same effect as the above instruction.

ADD A, 02h

Now, things get more complicated when we see that there are four banks of thesegeneral-purpose registers defined within the Internal RAM. For the moment we willconsider register bank 0 only. Register banks 1 to 3 can be ignored when writingintroductory level assembly language programs.

Page 24: Introduction to embeded system

Bit Addressable RAM: 20h to 2Fh

The 8051 supports a special feature which allows access to bit variables. This iswhere individual memory bits in Internal RAM can be set or cleared. In all there are128 bits numbered 00h to 7Fh. Being bit variables any one variable can have a value 0or 1. A bit variable can be set with a command such as SETB and cleared with acommand such as CLR. Example instructions are:

SETB 25h ; sets the bit 25h (becomes 1)CLR 25h ; clears bit 25h (becomes 0)

Note, bit 25h is actually bit b5 of Internal RAM location 24h.

The Bit Addressable area of the RAM is just 16 bytes of Internal RAM locatedbetween 20h and 2Fh. So if a program writes a byte to location 20h, for example, itwrites 8 bit variables, bits 00h to 07h at once.

General Purpose RAM: 30h to 7Fh

These 80 bytes of Internal RAM memory are available for general-purpose datastorage. Access to this area of memory is fast compared to access to the main memoryand special instructions with single byte operands are used. However, these 80 bytesare used by the system stack and in practice little space is left for general storage. Thegeneral purpose RAM can be accessed using direct or indirect addressing modes.Examples of direct addressing:

MOV A, 6Ah ; reads contents of address 6Ah to accumulatorExamples for indirect addressing (use registers R0 or R1):MOV R1, #6Ah ; move immediate 6Ah to R1MOV A, @R1 ; move indirect: R1 contains address of Internal RAM whichcontains data that is moved to A.These two instructions have the same effect as the direct instruction above.

SFR Registers

The SFR registers are located within the Internal Memory in the address range 80h toFFh, as shown in figure 1.7. Not all locations within this range are defined. Each SFRhas a very specific function. Each SFR has an address (within the range 80h to FFh)and a name which reflects the purpose of the SFR. Although 128 byes of the SFR address space is defined only 21 SFR registers are defined in the standard 8051.Undefined SFR addresses should not be accessed as this might lead to someunpredictable results. Note some of the SFR registers are bit addressable. SFRs areaccessed just like normal Internal RAM locations.

Page 25: Introduction to embeded system

Figure 1.7 SFR register layout

Port Registers SFR

The standard 8051 has four 8 bit I/O ports: P0, P1, P2 and P3. Read (input) and write(Output) access to this port is done in software by accessing the SFR P0 register whichis located at address 80h. SFR P0 is also bit addressable. Each bit corresponds to aphysical I/O pin on the 8051.

Example access to port 0:SETB P0.7 ; sets the MSB bit of Port 0CLR P0.7 ; clears the MSB bit of Port 0

The operand P0.7 uses the dot operator and refers to bit 7 of SFR P0. The same bitcould be addressed by accessing bit location 87h. Thus the following two instructions have the same meaning:CLR P0.7CLR 87h

Page 26: Introduction to embeded system

PSW Program Status Word

PSW, the Program Status Word is at address D0h and is a bit-addressable register.The status bits are listed in table.

Program status word (PSW) flags

Symbol Bit Address Description

C (or CY) PSW.7 D7h Carry flagAC PSW.6 D6h Auxiliary carry flagF0 PSW.5 D5h Flag 0RS1 PSW.4 D4h Register bank select 1RS0 PSW.3 D3h Register bank select 00V PSW.2 D2h Overflow flag

PSW.1 D1h ReservedP PSW.0 D0h Even Parity flag

Carry flag. C

This is a conventional carry, or borrow, flag used in arithmetic operations. The carryflag is also used as the ‘Boolean accumulator’ for Boolean instruction operating at thebit level. This flag is sometimes referenced as the CY flag.

Auxiliary carry flag. AC

This is a conventional auxiliary carry (half carry) for use in BCD arithmetic.

Flag 0. F0

This is a general-purpose flag for user programming.

Register bank select 0 and register bank select 1. RS0 and RS1

These bits define the active register bank (bank 0 is the default register bank).

Overflow flag. OV

This is a conventional overflow bit for signed arithmetic to determine if the result of asigned arithmetic operation is out of range.

Even Parity flag. P

The parity flag is the accumulator parity flag, set to a value, 1 or 0, such that thenumber of ‘1’ bits in the accumulator plus the parity bit add up to an even number.

Stack PointerThe Stack Pointer, SP, is an 8-bit SFR register at address 81h. The small address field(8 bits) and the limited space available in the Internal RAM confines the stack sizeand this is sometimes a limitation for 8051 programmers. The SP contains the address

Page 27: Introduction to embeded system

of the data byte currently on the top of the stack. The SP pointer in initialised to adefined address. A new data item is ‘pushed’ on to the stack using a PUSH instructionwhich will cause the data item to be written to address SP + 1. Typical instructions,which cause modification to the stack are: PUSH, POP, LCALL, RET, RETI etc.. TheSP SFR, on start-up, is initialised to 07h so this means the stack will start at 08h andexpand upwards in Internal RAM. If register banks 1 to 3 are to be used the SP SFRshould be initialised to start higher up in Internal RAM. The following instruction isoften used to initialise the stack:

MOV SP, #2Fh

Data PointerThe Data Pointer, DPTR, is a special 16-bit register used to address the external codeor external data memory. Since the SFR registers are just 8-bits wide the DPTR isstored in two SFR registers, where DPL (82h) holds the low byte of the DPTR andDPH (83h) holds the high byte of the DPTR. For example, if you wanted to write thevalue 46h to external data memory location 2500h, you might use the followinginstructions:

MOV A, #46h ; Move immediate 8 bit data 46h to A (accumulator)

MOV DPTR, #2504h ; Move immediate 16 bit address value 2504h to A.; Now DPL holds 04h and DPH holds25h.

MOVX @DPTR, A ; Move the value in A to external RAM location 2500h. Uses indirect addressing.

MOVX (Move X) instruction is used to access external memory.

Accumulator

This is the conventional accumulator that one expects to find in any computer, whichis used to the hold result of various arithmetic and logic operations. Since the 8051microcontroller is just an 8-bit device, the accumulator is, as expected, an 8 bitregister.

The accumulator, referred to as ACC or A, is usually accessed explicitly usinginstructions such as:

INC A ; Increment the accumulator

However, the accumulator is defined as an SFR register at address E0h. So thefollowing two instructions have the same effect:

MOV A, #52h ; Move immediate the value 52h to the accumulator

MOV E0h, #52h ; Move immediate the value 52h to Internal RAM location E0h, which is, in fact, the accumulator SFR register.

Page 28: Introduction to embeded system

B Register

The B register is an SFR register at addresses F0h which is bit-addressable. The Bregister is used in two instructions only: i.e. MUL (multiply) and DIV (divide). The Bregister can also be used as a general-purpose register.

Program Counter

The PC (Program Counter) is a 2 byte (16 bit) register which always contains thememory address of the next instruction to be executed. When the 8051 is reset the PCis always initialised to 0000h. If a 2 byte instruction is executed the PC is incrementedby 2 and if a 3 byte instruction is executed the PC is incremented by three so as tocorrectly point to the next instruction to be executed. A jump instruction (e.g. LJMP)has the effect of causing the program to branch to a newly specified location, so thejump instruction causes the PC contents to change to the new address value. Jumpinstructions cause the program to flow in a non-sequential fashion, as will bedescribed later.

SFR Registers for the Internal Timer

The set up and operation of the on-chip hardware timers will be described later, butthe associated registers are briefly described here:

TCON, the Timer Control register is an SFR at address 88h, which is bit-addressable.TCON is used to configure and monitor the 8051 timers. The TCON SFR alsocontains some interrupt control bits, described later.

TMOD, the Timer Mode register is an SFR at address 89h and is used to define theoperational modes for the timers, as will be described later.

TL0 (Timer 0 Low) and TH0 (Timer 0 High) are two SFR registers addressed at 8Ahand 8Bh respectively. The two registers are associated with Timer 0.

TL1 (Timer 1 Low) and TH1 (Timer 1 High) are two SFR registers addressed at 8Chand 8Dh respectively. These two registers are associated with Timer 1.

Power Control Register

PCON (Power Control) register is an SFR at address 87h. It contains various controlbits including a control bit, which allows the 8051 to go to ‘sleep’ so as to save powerwhen not in immediate use.

Serial Port Registers

Programming of the on-chip serial communications port will be described later in thetext. The associated SFR registers, SBUF and SCON, are briefly introduced here, asfollows:

The SCON (Serial Control) is an SFR register located at addresses 98h, and it is bit addressable.

Page 29: Introduction to embeded system

SCON configures the behavior of the on-chip serial port, setting upparameters such as the baud rate of the serial port, activating send and/or receive data,and setting up some specific control flags.

The SBUF (Serial Buffer) is an SFR register located at address 99h. SBUF is just asingle byte deep buffer used for sending and receiving data via the on-chip serial port.

Interrupt Registers

Interrupts will be discussed in more detail later. The associated SFR registers are:

IE (Interrupt Enable) is an SFR register at addresses A8h and is used to enable anddisable specific interrupts. The MSB bit (bit 7) is used to disable all interrupts.

IP (Interrupt Priority) is an SFR register at addresses B8h and it is bit addressable.The IP register specifies the relative priority (high or low priority) of each interrupt.On the 8051, an interrupt may either be of low (0) priority or high (1) priority.

ADDRESSING MODES

There are a number of addressing modes available to the 8051 instruction set, asfollows:Immediate Addressing Register Addressing Direct AddressingIndirect Addressing Relative Addressing Absolute addressingLong Addressing Indexed Addressing

Immediate Addressing

Immediate addressing simply means that the operand (which immediately follows theinstruction op. code) is the data value to be used. For example the instruction:

MOV A, #99d

Moves the value 99 into the accumulator (note this is 99 decimal since we used 99d).The # symbol tells the assembler that the immediate addressing mode is to be used.

Register Addressing

One of the eight general-registers, R0 to R7, can be specified as the instructionoperand. The assembly language documentation refers to a register generically as Rn.An example instruction using register addressing is :

ADD A, R5 ; Adds register R5 to A (accumulator)Here the contents of R5 is added to the accumulator. One advantage of registeraddressing is that the instructions tend to be short, single byte instructions.

Page 30: Introduction to embeded system

Direct Addressing

Direct addressing means that the data value is obtained directly from the memorylocation specified in the operand. For example consider the instruction:

MOV A, 47h

The instruction reads the data from Internal RAM address 47h and stores this in theaccumulator. Direct addressing can be used to access Internal RAM , including theSFR registers.

Indirect Addressing

Indirect addressing provides a powerful addressing capability, which needs to beappreciated. An example instruction, which uses indirect addressing, is as follows:

MOV A, @R0

Note the @ symbol indicated that the indirect addressing mode is used. R0 contains avalue, for example 54h, which is to be used as the address of the internal RAM location, which contains the operand data. Indirect addressing refers to Internal RAMonly and cannot be used to refer to SFR registers.

Note, only R0 or R1 can be used as register data pointers for indirect addressing whenusing MOV instructions.

The 8052 (as opposed to the 8051) has an additional 128 bytes of internal RAM.These 128 bytes of RAM can be accessed only using indirect addressing.

Relative Addressing

This is a special addressing mode used with certain jump instructions. The relativeaddress, often referred to as an offset, is an 8-bit signed number, which isautomatically added to the PC to make the address of the next instruction. The 8-bitsigned offset value gives an address range of + 127 to –128 locations. Consider thefollowing example:

SJMP LABEL_X

An advantage of relative addressing is that the program code is easy to relocate inmemory in that the addressing is relative to the position in memory.

Absolute addressing

Absolute addressing within the 8051 is used only by the AJMP (Absolute Jump) andACALL (Absolute Call) instructions, which will be discussed later.

Long AddressingThe long addressing mode within the 8051 is used with the instructions LJMP andLCALL. The address specifies a full 16 bit destination address so that a jump or a call

Page 31: Introduction to embeded system

can be made to a location within a 64KByte code memory space (216 = 64K). Anexample instruction is:

LJMP 5000h ; full 16 bit address is specified in operand.

Indexed Addressing

With indexed addressing a separate register, either the program counter, PC, or thedata pointer DTPR, is used as a base address and the accumulator is used as an offsetaddress. The effective address is formed by adding the value from the base address tothe value from the offset address. Indexed addressing in the 8051 is used with theJMP or MOVC instructions. Look up tables are easy to implemented with the help ofindex addressing. Consider the example instruction:

MOVC A, @A+DPTR

MOVC is a move instruction, which moves data from the external code memoryspace. The address operand in this example is formed by adding the content of theDPTR register to the accumulator value. Here the DPTR value is referred to as thebase address and the accumulator value us referred to as the index address.

Page 32: Introduction to embeded system

ASSEMBLY LANGUAGE PROGRAMMING

Number Representation for Different Bases

The following is an example showing the decimal number 46 represented in differentnumber bases:

46d ; 46 decimal2Eh ; 2Eh is 46 decimal represented as a hex number56o ; 56o is 46 decimal represented as an octal number101110b ; 101110b is 46 decimal represented as a binary number.

Note a number digit must be used in the first character of a hexadecimal number. Forexample the hexadecimal number A5h is illegally represented and should berepresented as 0A5h.

The Arithmetic Operators

The arithmetic operators are:+ add- subtract* multiply/ divideMOD modulo (result is the remainder following division)

The Logical Operators

The logical operators are:AND Logical ANDOR Logical ORXOR Logical XOR (exclusive OR)NOT Logical NOT

The Relational Operators

The result of a relational operation is either true (represented by minus 1), or false(represented by zero). The relational operators are:Equal to EQ =not equal to NE <>greater than GT >greater than or equal to GE >=less than LT <less than or equal to LE <=

(note ‘EQ’ symbol and ‘= ‘ symbol have the same meaning)

Operator Precedence

Like a high level language, assembly level programs define operator predence.Operators with same precedence are evaluated left to right. Note, brackets ( ) means to

Page 33: Introduction to embeded system

evaluate this first. HIGH indicates the high-byte and LOW indicates the low-byte.Later examples will clarify the use of such special operators. The precedence list,highest first, is as follows:

( )HIGH LOW* / MOD SHL SHR+ -= <> < <= > >=NOTANDOR XOR

Some Assembler Directives

The assembler directives are special instruction to the assembler program to definesome specific operations but these directives are not part of the executable program.Some of the most frequently assembler directives are listed as follows:

ORG Originate, defines the starting address for the program in program(Code) memory

EQU Equate, assigns a numeric value to a symbol identifier so as to makethe program more readable.

DB Define a Byte, puts a byte (8-bit number) number constant at thismemory location

DW Define a Word, puts a word (16-bit number) number constant at thismemory location

DBIT Define a Bit, defines a bit constant, which is stored in the bitaddressable section if the Internal RAM.

END This is the last statement in the source file to advise the assembler tostop the assembly process.

Types of Instructions

The assembly level instructions include: data transfer instructions, arithmeticinstructions, logical instructions, program control instructions, and some specialinstructions such as the rotate instructions.

Data Transfer

Many computer operations are concerned with moving data from one location toanother. The 8051 uses five different types of instruction to move data:

MOV MOVX MOVCPUSH and POP XCH

Page 34: Introduction to embeded system

MOV

In the 8051 the MOV instruction is concerned with moving data internally, i.e.between Internal RAM, SFR registers, general registers etc. MOVX and MOVC areused in accessing external memory data. The MOV instruction has the followingformat:

MOV destination <- source

The instruction copies (copy is a more accurate word than move) data from a definedsource location to a destination location. Example MOV instructions are:

MOV R2, #80h ; Move immediate data value 80h to register R2MOV R4, A ; Copy data from accumulator to register R4MOV DPTR, #0F22Ch ; Move immediate value F22Ch to the DPTR registerMOV R2, 80h ; Copy data from 80h (Port 0 SFR) to R2MOV 52h, #52h ; Copy immediate data value 52h to RAM location 52hMOV 52h, 53h ; Copy data from RAM location 53h to RAM 52hMOV A, @R0 ; Copy contents of location addressed in R0 to A

(indirect addressing)

MOVX

The 8051 the external memory can be addressed using indirect addressing only. TheDPTR register is used to hold the address of the external data (since DPTR is a 16-bitregister it can address 64KByte locations: 216 = 64K). The 8 bit registers R0 or R1 canalso be used for indirect addressing of external memory but the address range islimited to the lower 256 bytes of memory (28 = 256 bytes).

The MOVX instruction is used to access the external memory (X indicates eXternalmemory access). All external moves must work through the A register (accumulator).Examples of MOVX instructions are:

MOVX @DPTR, A ; Copy data from A to the address specified in DPTRMOVX A, @DPTR ; Copy data from address specified in DPTR to A

MOVC

MOVX instructions operate on RAM, which is (normally) a volatile memory.Program tables often need to be stored in ROM since ROM is non volatile memory.The MOVC instruction is used to read data from the external code memory (ROM).Like the MOVX instruction the DPTR register is used as the indirect address register.The indirect addressing is enhanced to realise an indexed addressing mode whereregister A can be used to provide an offset in the address specification. Like theMOVX instruction all moves must be done through register A. The followingsequence of instructions provides an example:

MOV DPTR, # 2000h ; Copy the data value 2000h to the DPTR registerMOV A, #80h ; Copy the data value 80h to register A

Page 35: Introduction to embeded system

MOVC A, @A+DPTR ; Copy the contents of the address 2080h (2000h + 80h); to register A

For the MOVC the program counter, PC, can also be used to form the address.

PUSH and POP

PUSH and POP instructions are used with the stack only. The SFR register SPcontains the current stack address. Direct addressing is used as shown in the followingexamples:

PUSH 4Ch ; Contents of RAM location 4Ch is saved to the stack. SP is incremented.

PUSH 00h ; The content of R0 (which is at 00h in RAM) is saved to the stack and SP is incremented.

POP 80h ; The data from current SP address is copied to 80h and SP is decremented.

XCH

The above move instructions copy data from a source location to a destinationlocation, leaving the source data unaffected. A special XCH (exchange) instructionwill actually swap the data between source and destination, effectively changing thesource data. Immediate addressing may not be used with XCH. XCH instructionsmust use register A. XCHD is a special case of the exchange instruction where justthe lower nibbles are exchanged. Examples using the XCH instruction are:

XCH A, R3 ; Exchange bytes between A and R3XCH A, @R0 ; Exchange bytes between A and RAM location whose address is in R0XCH A, A0h ; Exchange bytes between A and RAM location A0h (SFR port 2)

Arithmetic

Some key flags within the PSW, i.e. C, AC, OV, P, are utilised in many of thearithmetic instructions. The arithmetic instructions can be grouped as follows:

AdditionSubtractionIncrement/decrementMultiply/divideDecimal adjust

Addition

Register A (the accumulator) is used to hold the result of any addition operation.Some simple addition examples are:

ADD A, #25h ; Adds the number 25h to A, putting sum in AADD A, R3 ; Adds the register R3 value to A, putting sum in A

Page 36: Introduction to embeded system

The flags in the PSW register are affected by the various addition operations, as follows:

The C (carry) flag is set to 1 if the addition resulted in a carry out of the accumulator’sMSB bit, otherwise it is cleared.

The AC (auxiliary) flag is set to 1 if there is a carry out of bit position 3 of theaccumulator, otherwise it is cleared.

For signed numbers the OV flag is set to 1 if there is an arithmetic overflow

Simple addition is done within the 8051 based on 8 bit numbers, but it is oftenrequired to add 16 bit numbers, or 24 bit numbers etc. This leads to the use ofmultiple byte (multi-precision) arithmetic. The least significant bytes are first added,and if a carry results, this carry is carried over in the addition of the next significantbyte etc. This addition process is done at 8-bit precision steps to achieve multiprecisionarithmetic. The ADDC instruction is used to include the carry bit in theaddition process. Example instructions using ADDC are:

ADDC A, #55h ; Add contents of A, the number 55h, the carry bit; and put the sum in A

ADDC A, R4 ; Add the contents of A, the register R4, the carry bit; and put the sum in A.

SubtractionComputer subtraction can be achieved using 2’s complement arithmetic. Mostcomputers also provide instructions to directly subtract signed or unsigned numbers.The accumulator, register A, will contain the result (difference) of the subtractionoperation. The C (carry) flag is treated as a borrow flag, which is always subtractedfrom the minuend during a subtraction operation. Some examples of subtractioninstructions are:

SUBB A, #55d ; Subtract the number 55 (decimal) and the C flag from A; and put the result in A.

SUBB A, R6 ; Subtract R6 the C flag from A; and put the result in A.SUBB A, 58h ; Subtract the number in RAM location 58h and the C flag

From A; and put the result in A.

Increment/Decrement

The increment (INC) instruction has the effect of simply adding a binary 1 to anumber while a decrement (DEC) instruction has the effect of subtracting a binary 1from a number. The increment and decrement instructions can use the addressingmodes: direct, indirect and register. The flags C, AC, and OV are not affected by theincrement or decrement instructions. If a value of FFh is increment it overflows to00h. If a value of 00h is decrement it underflows to FFh. The DPTR can overflowfrom FFFFh to 0000h. The DPTR register cannot be decremented using a DECinstruction (unfortunately!). Some example INC and DEC instructions are as follows:

INC R7 ; Increment register R7INC A ; Increment A

Page 37: Introduction to embeded system

INC @R1 ; Increment the number which is the content of the address in R1DEC A ; Decrement register ADEC 43h ; Decrement the number in RAM address 43hINC DPTR ; Increment the DPTR register

Multiply / Divide

The 8051 supports 8-bit multiplication and division. This is low precision (8 bit)arithmetic but is useful for many simple control applications. The arithmetic isrelatively fast since multiplication and division are implemented as singleinstructions. If better precision, or indeed, if floating point arithmetic is required thenspecial software routines need to be written. For the MUL or DIV instructions the Aand B registers must be used and only unsigned numbers are supported.

Multiplication

The MUL instruction is used as follows (note absence of a comma between the A andB operands):

MUL AB ; Multiply A by B.

The resulting product resides in registers A and B, the low-order byte is in A and thehigh order byte is in B.

Division

The DIV instruction is used as follows:

DIV AB ; A is divided by B.

The remainder is put in register B and the integer part of the quotient is put in register A.

Decimal Adjust (Special)

The 8051 performs all arithmetic in binary numbers (i.e. it does not support BCDarithmetic). If two BCD numbers are added then the result can be adjusted by usingthe DA, decimal adjust, instruction:

DA A ; Decimal adjust A following the addition of two BCD numbers.

Logical

Boolean Operations

Most control applications implement control logic using Boolean operators to act onthe data. Most microcomputers provide a set of Boolean instructions that act on bytelevel data. However, the 8051 (somewhat uniquely) additionally provides Booleaninstruction which can operate on bit level data.

The following Boolean operations can operate on byte level or bit level data:

Page 38: Introduction to embeded system

ANL Logical ANDORL Logical ORCPL Complement (logical NOT)XRL Logical XOR (exclusive OR)

Logical operations at the BYTE level

The destination address of the operation can be the accumulator (register A), ageneral register, or a direct address. Status flags are not affected by these logicaloperations (unless PSW is directly manipulated). Example instructions are:

ANL A, #55h ; AND each bit in A with corresponding bit in number 55h, leaving the result in A.

ANL 42h, R4 ; AND each bit in RAM location 42h with corresponding bit in R4, leaving the result in RAM location 42h.

ORL A,@R1 ; OR each bit in A with corresponding bit in the number whose address is contained in R1 leaving the result in A.

XRL R4, 80h ; XOR each bit in R4 with corresponding bit in RAM location 80h (port 0), leaving result in A.

CPL R0 ; Complement each bit in R0

Logical operations at the BIT level

The C (carry) flag is the destination of most bit level logical operations. The carry flagcan easily be tested using a branch (jump) instruction to quickly establish programflow control decisions following a bit level logical operation.

The following SFR registers only are addressable in bit level operations:

PSW IE IP TCON SCON

Examples of bit level logical operations are as follows:

SETB 2Fh ; Bit 7 of Internal RAM location 25h is setCLR C ; Clear the carry flag (flag =0)CPL 20h ; Complement bit 0 of Internal RAM location 24hMOV C, 87h ; Move to carry flag the bit 7of Port 0 (SFR at 80h)ANL C,90h ; AND C with the bit 0 of Port 1 (SFR at 90)ORL C, 91h ; OR C with the bit 1 of Port 1 (SFR at 90)

Rotate Instructions

The ability to rotate the A register (accumulator) data is useful to allow examinationof individual bits. The options for such rotation are as follows:

RL A ; Rotate A one bit to the left. Bit 7 rotates to the bit 0 position

Page 39: Introduction to embeded system

RLC A ; The Carry flag is used as a ninth bit in the rotation loop

RR A ; Rotates A to the right (clockwise)

RRC A ; Rotates to the right and includes the carry bit as the 9th bit.

Swap = special

The Swap instruction swaps the accumulator’s high order nibble with the low-ordernibble using the instruction:

SWAP A

Program Control Instructions

The 8051 supports three kind of jump instructions:

LJMP SJMP AJMP

LJMP

LJMP (long jump) causes the program to branch to a destination address defined bythe 16-bit operand in the jump instruction. Because a 16-bit address is used the instruction can cause a jump to any location within the 64KByte program space (216 =64K). Some example instructions are:

LJMP LABEL_X ; Jump to the specified labelLJMP 0F200h ; Jump to address 0F200hLJMP @A+DPTR ; Jump to address which is the sum of DPTR and Reg. A

SJMP

SJMP (short jump) uses a singe byte address. This address is a signed 8-bit numberand allows the program to branch to a distance –128 bytes back from the current PCaddress or +127 bytes forward from the current PC address. The address mode usedwith this form of jumping (or branching) is referred to as relative addressing,introduced earlier, as the jump is calculated relative to the current PC address.

AJMP

This is a special 8051 jump instruction, which allows a jump with a 2KByte addressboundary (a 2K page)

There is also a generic JMP instruction supported by many 8051 assemblers. Theassembler will decide which type of jump instruction to use, LJMP, SJMP or AJMP,so as to choose the most efficient instruction.

Subroutines and program flow controlA suboutine is called using the LCALL or the ACALL instruction.

Page 40: Introduction to embeded system

LCALL

This instruction is used to call a subroutine at a specified address. The address is 16bits long so the call can be made to any location within the 64KByte memory space.When a LCALL instruction is executed the current PC content is automaticallypushed onto the stack of the PC. When the program returns from the subroutine thePC contents is returned from the stack so that the program can resume operation fromthe point where the LCALL was made

The return from subroutine is achieved using the RET instruction, which simply popsthe PC back from the stack

ACALL

The ACALL instruction is logically similar to the LCALL but has a limited addressrange similar to the AJMP instruction.

CALL is a generic call instruction supported by many 8051 assemblers. Theassembler will decide which type of call instruction, LCALL or ACALL, to use so asto choose the most efficient instruction.

Program control using conditional jumps

Most 8051 jump instructions use an 8-bit destination address, based on relativeaddressing, i.e. addressing within the range –128 to +127 bytes.When using a conditional jump instruction the programmer can simply specify aprogram label or a full 16-bit address for the conditional jump instruction’sdestination. The assembler will position the code and work out the correct 8-bitrelative address for the instruction. Some example conditional jump instructions are:

JZ LABEL_1 ; Jump to LABEL_1 if accumulator is equal to zeroJNZ LABEL_X ; Jump to LABEL_X if accumulator is not equal to zeroJNC LABEL_Y ; Jump to LABEL_Y if the carry flag is not setDJNZ R2, LABEL ; Decrement R2 and jump to LABEL if the resulting value of

R2 is not zero.CJNE R1, #55h , LABEL_2

; Compare the magnitude of R1 and the number 55h and jump to LABEL_2 if the magnitudes are not equal.

Jump instructions such as DJNZ and CJNE are very powerful as they carry out aparticular operation (e.g.: decrement, compare) and then make a decision based on theresult of this operation. Some example code later will help to explain the context inwhich such instructions might be used.

OPERATION OF THE STACK POINTER

When a subroutine is called the current content of the Program Counter (PC) is saveto the stack, the low byte of the PC is save first, followed by the high byte. Thus theStack Pointer (SP) in incremented by 2. When a RET (return from subroutine)instruction is executed the stored PC value on the stack is restored to the PC, thus

Page 41: Introduction to embeded system

decrementing the SP by 2.

When a byte is Pushed to the stack, the SP in incremented by one so as to point tothe next available stack location. Conversely, when a byte is POP’ed from the stackthe SP is decremented by one.

Page 42: Introduction to embeded system

8051 INTERRUPTS

There are five interrupt sources for the 8051. Since the main RESET input can also beconsidered as an interrupt, six interrupts can be listed as follows:

Interrupt Flag Vector address-----------------------------------------------------------------------------------System RESET RST 0000hExternal interrupt 0 IE0 0003hTimer/counter 0 TF0 000BhExternal interrupt 1 IE1 0013hTimer/counter 1 TF1 001BhSerial port RI or TI 0023h

We will concentrate on the external interrupts for now, and later we will examine theother interrupt sources. Here’s a brief look at some of the register bits which will beused to set up the interrupts in the example programs.

The Interrupt Enable, IE, register is an SFR register at location A8h in Internal RAM.The EA bit will enable all interrupts (when set to 1) and the individual interrupts mustalso be enabled.Interrupt Enable register

EAMsb

ES ET1 EX1 ET0 EX0Lsb

For example, if we want to enable the two external interrupts we would use theinstruction:

MOV IE, #10000101B

Each of the two external interrupt sources can be defined to trigger on the externalsignal, either on a negative going edge or on a logic low level state. The negative edgetrigger is usually preferred as the interrupt flag is automatically cleared by hardware,in this mode. Two bits in the TCON register are used to define the trigger operation.The TCON register is another SFR register and is located at location 88h in InternalRAM. The other bits in the TCON register will be described later in the context of thehardware Timer/Counters.

TCON Register

MsbIT1 IT0

Lsb

To define negative edge triggering for the two external interrupts use instructions asfollows:SETB IT0 ; negative edge trigger for interrupt 0SETB IT1 ; negative edge trigger for interrupt 1Figure shows the flow of operation when a system is interrupted. In the example it is assumed that some program, say the main program, is executing when the externalinterrupt INT0 occurs. The 8051 hardware will automatically complete the current

Page 43: Introduction to embeded system

machine level (assembler level) instruction and save the Program Counter to thestack. The IE register is also saved to the stack. The IE0 flag is disabled (cleared) sothat another INT0 interrupt will be inhibited while the current interrupt is beingserviced. The Program Counter is now loaded with the vector location 0003h. Thisvector address is a predefined address for interrupt INT0 so that program executionwill always trap to this address when an INT0 interrupt occurs. Other interruptsources have uniquely defined vector addresses for this purpose. The set of thesevector addresses is referred to as the interrupt vector table.Program execution is now transferred to address location 0003h. In the example aLJMP instruction is programmed at this address to cause the program to jump to apredefined start address location for the relevant ISR (Interrupt Service Routine)routine. The ISR routine is a user written routine, which defines what action is tooccur following the interrupt event. It is good practice to save (PUSH) to the stackany registers used during the ISR routine and to restore (POP) these registers at theend of the ISR routine, thus preserving the registers’ contents, just like a register ispreserved within a subroutine program. The last instruction in the ISR routine is aRETI (RETurn from Interrupt) instruction and this instruction causes the 8051 torestore the IE register values, enable the INT0 flag, and restore the Program Countercontents from the stack.Since the Program Counter now contains the address of the next instruction whichwas to be executed before the INT0 interrupt occurred, the main program continues asif it had never being interrupted. Thus only the temporal behaviour of the interruptedprogram has been affected by the interrupt; the logic of the program has not beenotherwise affected.

Interrupt operation

Page 44: Introduction to embeded system

OTHER SOURCES OF INTERRUPTS

Figure shows the set of 8051 interrupt sources. If we follow the external interruptINT0, for example, we see that this external interrupt connects to the processor at theP3.2 pin. Note Port 3 can be used as a standard input/output port as shown earlier –but various Port 3 pins have alternative functionality. When INT0 is activated(negative edge usually), internally within the 8051 the EX0 request is raised. Thisflags an interrupt request but the relevant interrupt bit within the IE register must beset, along with the EA bit if this interrupt request is to raise an interrupt flag. Theinterrupt flag IE0 is then raised and causes the program counter (PC) to vector tovector location 0003h, as discussed earlier. Note, the Timer/Counter interrupt flagscan be software polled even if the ETx bits are not enabled. Interrupts can also besoftware generated by setting the interrupt flags in software. The interrupt flags areaccessible as flags on the TCON and SCON registers as follows:

TCON Register

TF1Msb

TF0 IE1 IT1 IE0 IT0Lsb

SCON Register

MsbTI RI

Lsb

Interrupt sources

Page 45: Introduction to embeded system

INTERRUPT PRIORITY LEVEL STRUCTURE

An individual interrupt source can be assigned one of two priority levels. TheInterrupt Priority, IP, register is an SFR register used to program the priority level foreach interrupt source. A logic 1 specifies the high priority level while a logic 0specifies the low priority level.

IP register

xmsb

x PT2 PS PT1 PX1 PT1 PX0lsb

IP.7 x reservedIP.6 x reservedIP.5 PT2 Timer/counter-2 interrupt priority (8052 only, not 8051)IP.4 PS Serial port interrupt priorityIP.3 PT1 Timer/Counter-1 interrupt priorityIP.2 PX1 External interrupt-1 priorityIP.1 PT0 Timer/Counter-0 interrupt priorityIP.0 PX0 External interrupt-0 priority

An ISR routine for a high priority interrupt cannot be interrupted. An ISR routine fora low priority interrupt can be interrupted by a high priority interrupt, but not by a lowpriority interrupt.

If two interrupt requests, at different priority levels, arrive at the same time then thehigh priority interrupt is serviced first. If two, or more, interrupt requests at the samepriority level arrive at the same time then the interrupt to be serviced is selected basedon the order shown below. Note, this order is used only to resolve simultaneousrequests. Once an interrupt service begins it cannot be interrupted by another interruptat the same priority level.

Interrupt Priority withinsource a given levelIE0 highestTF0IE1TF1RI, TITF2 (8052, not 8051) lowest

Page 46: Introduction to embeded system

Timer/Counters

The 8051 has two internal sixteen bit hardware Timer/Counters. Each Timer/Countercan be configured in various modes, typically based on 8-bit or 16-bit operation. The8052 product has an additional (third) Timer/Counter.

Figure provides us with a brief refresher on what a hardware counter looks like.This is a circuit for a simple 3-bit counter which counts from 0 to 7 and thenoverflows, setting the overflow flag. A 3-bit counter would not be very useful in amicrocomputer so it is more typical to find 8-bit and 16-bit counter circuits.

Fig. 3-bit counter circuit

8-bit TIMER OPERATION

The 8051 internally divides the processor clock by 12. If a 12 MHz. processor clock isused then a 1 MHz. instruction rate clock, or a pulse once every microsecond, isrealised internally within the chip. If this 1 microsecond pulse is connected to aTimer/Counter input, in place of an event input, then the Timer/Counter becomes atimer which can delay by up to 255 microseconds. There is a clear difference betweena timer and a counter. The counter will count events, up to 255 events beforeoverflow, and the timer will count time pulses, thus creating delays up to 255microseconds in our example.

To be precise we would refer to the counter as an event counter and we would refer tothe timer as an interval timer.If the timer is initialised to zero it will count 256 microseconds before overflow. If thetimer is initialised to a value of 252, for example, it will count just 4 microseconds

Page 47: Introduction to embeded system

before overflow. Thus this timer is programmable between 1 microsecond and 256microseconds.

PROGRAMING THE 8-BIT TIMER

Let’s look at how to do the following:o Configure the Timer/Counter as a TIMER or as a COUNTERo Program the Timer/Counter with a value between 0 and 255o Enable and disable the Timer/Countero How to know when the timer has overflowed – interrupt vs. polling.

The TMOD register (Timer Mode Control) is an SFR register at location 89h ininternal RAM and is used to define the Timer/Counter mode of operation.

TMOD Register

Gatemsb

C/T M1 M0 Gate C/T M1 M0lsb

-------------------------timer1--------------------|------------------------timer0----------------------

Consider Timer/Counter 1 only. The Gate bit will be ignored for now and will be setto 0 in the examples. The C/T bit is set to 1 for COUNTER operation and it is set to 0for TIMER operation. MI and M2 bits define different modes, where mode 2 is the 8bit mode, i.e.:

M1 M00 0 mode 0: 13 bit mode (seldom used).0 1 mode 1: 16-bit mode1 0 mode 2: 8-bit mode (with auto reload feature)1 1 mode 3: ignore for now

To run in TIMER mode using 8-bit operation, the TMOD register is initialized as follows:

MOV TMOD, #00100000b ; assume timer 0 is not considered

Program the Timer/Counter value

The 8-bit Timer/Counter is pre-programmed with a value in the range 0..255. This isachieved by writing this value into the TH1 register for the Timer/Counter. TH1 is anSFR register (located at 8Dh in Internal RAM). An example is as follows:

MOV TH1, #129d ; Timer/Counter 1 is programmed for 129 counts

Page 48: Introduction to embeded system

THE 16 BIT TIMER/CONTER

When the Timer/Counter is configured for mode 1 operation it operates in 16 bitmode. Since this is a modulo-16 set up we are concerned with 65,536 numbers in therange 0 to 65,535 (216 = 65,536). Consider a 16 bit Timer/Counter as shown below,which will count in the sequence as follows:

Hex Binary Decimal0000h 0000000000000000 00001h 0000000000000001 10010h 0000000000000010 2. . .. . .FFFEh 1111111111111110 65,534FFFFh 1111111111111111 65,53500000h 0000000000000000 0 here it overflows to zero

Now we have a 16-bit Timer/Counter and we can preload it with a sixteen bit numberso as to cause a delay from between 1 to 65,535 microseconds (65.535 milli secs.), orin counter mode it can count between 1 and 65,535 events. To preload theTimer/Counter value simply write the most significant byte into the TH1 register andthe least significant byte into the TL1 register. The 16-bit counter is not automaticallyreloaded following an overflow and such reloading must be explicitly programmed.

Page 49: Introduction to embeded system

The 8051 Serial Port

OVERVIEW OF ASYNCHRONOUS SERIAL COMMUNICATIONS

RS-232 Serial Communications

The EIA RS-232 serial communication standard is a universal standard, originallyused to connect teletype terminals to modem devices. Figure 6.1(a) shows a PCconnected to a device such as a modem or a serial printer using the RS-232connection. In a modern PC the RS-232 interface is referred to as a COM port. TheCOM port uses a 9-pin D-type connector to attach to the RS-232 cable. The RS-232standard defines a 25-pin D-type connector but IBM reduced this connector to a 9-pindevice so as to reduce cost and size. Figure 6.1(b) shows a simple simplex serialcommunication link where data is being transmitted serially from left to right. Asingle Tx (transmit) wire is used for transmission and the return (Gnd) wire isrequired to complete the electrical circuit. Figure 6.1(c) shows the inclusion ofanother physical wire to support full-duplex (or half-duplex) serial communication.The RS-232 (COM port) standard includes additional signal wires for “hand-shake”purposes, but the fundamental serial communication can be achieved with just two orthree wires as shown.

The serial data is transmitted at a predefined rate, referred to as the baud rate. Theterm baud rate refers to the number of state changes per second which is the same asthe bit rate for this particular communication scheme. Typical baud rates are: 9600bps; 19,200 bps; 56kbps etc.

Page 50: Introduction to embeded system

Two way communication using three wiresFIG. Serial communications

Asynchronous Serial Communications

Since data is sent is a serial fashion, without any reference to a timing clock to helpsynchronise the receiver clock in terms of frequency and phase, the system is said tobe non-synchronous, or asynchronous. The baud rate clocks at each end of the RS-232link are set to the same frequency values but there is no mechanism to synchronisethese clocks. Figure 6.2(a) shows three bytes transmitted by the PC. Assume the bytesare ascii coded to represent the characters A, B and C. The receiver needs to knowexactly where each character starts and finishes. To achieve this the data character isframed with a start bit at the beginning of each character and a stop bit at the end ofeach character. Figure 6.2(b) shows the start bit as a low logic level and the stop bit asa high logic level. Thus the receiver can detect the start bit and it then clocks in the next eight character bits. The receiver then expects to find the stop bit, existing as a logic highbit. This is a crude form of synchronisation applied to a system which is inherently non-synchronous. A high price is paid for this form of synchronisation in terms ofbandwidth, as for every eight bits of data transmitted two bits are required to supportthe framing. Ten bits are transmitted to support eight bits of data thus the scheme is, atbest, just eighty percent efficient. Figure 6.2(c) shows the inclusion of an additionalparity bit for error control purposes.

Page 51: Introduction to embeded system

Single Bit Parity for Error CheckingAll communication systems are prone to errors. An RS-232 communication system issusceptible to bit errors as data bits can become corrupted (bit changes from 1 to 0 orfrom 0 to 1). Such corruption is often caused by unwanted electrical noise coupledinto the wiring. Figure shows an example where an 8-bit data character is transmitted and a single bit becomes corrupted during transmission. The receiver gets the wrong data. Figure show a single bit parity scheme where the parity bit is calculated at the transmitter and this parity bit is sent along with the eight data bits. The receiver can apply a test on the received data to establish whether or not an error exists in the received data. In this example even parity is used. The parity bit is calculated at the transmitter so that all of the bits, including the parity bit add up to an even number of ones. Thus, in the example, the parity bit is set to 0 so that an even number of ones exists across the 9 bits. The receiver checks the received data for even parity and in this case finds that the parity test fails. The receiver now knows that an error exists and it is up to a higher layer protocol to act on the error. Note, the receiver does not know which bit is in error, it is simply aware than an error exist in the received data. If the parity bit itself had been corrupted the same parity test would detect this error also. If any odd number of bits (1, 3, 5, 7 or 9 bits) are in error the simple parity test will detect the error. However, if an even number of bits are in error (2, 4, 6 or 8 bits) then such errors will go unnoticed in the parity test. Since the majority of errors in communication systems are single bit errors then the simple single bit parity scheme is worthwhile. There are more complex techniques used toprovide more rigorous error checking and error correction.

Page 52: Introduction to embeded system

THE 8051 UART

The 8051 includes a hardware UART to support serial asynchronous communicationsso that, typically, the product can support RS-232 standard communication. TheUART (Universal Asynchronous Receiver and Transmitter) block diagram is shownin figure 6.4. In our examples the BAUD clocks are, in fact, a single clock sourceprovided by Timer/Counter 1.

Figure UART block diagram

The UART can be configured for 9-bit data transmission and reception. Here 8 bitsrepresent the data byte (or character) and the ninth bit is the parity bit. Figure shows a block diagram for the UART transmitter, where the ninth bit is used as the parity bit.

Page 53: Introduction to embeded system

Figure: Block diagram of UART transmitter, using the 9th. bit

Figure shows a block diagram for the UART receiver, where the ninth bit is usedas the parity bit.

Figure: Block diagram of UART receiver, using the 9th. Bit

SBUF is an SFR register which can be written to, so as to hold the next data byte to betransmitted. Also it can be read from to get the latest data byte received by the serialport. SBUF is thus effectively two registers: one for transmitting and one forreceiving.

The SCON (Serial Control) register is an SFR register, used for configuring andmonitoring the serial port status.

SCON Register

SM0msb

SM1 SM2 REN TB8 RB8 TI RIlsb

Page 54: Introduction to embeded system

SM0, SM1 bits define the mode of operation, such as the number of data bits (8 or9), the clock source etc. Our examples will use mode 3, which specifies 9 data bits (8data plus a parity bit) with the clock source being Timer/Counter 1.

SM2 is set to 0 for normal operationREN is set to 1 to enable reception, 0 to disable receptionTB8 is the ninth bit (parity bit) to be transmittedRB8 is the ninth bit received (parity bit)TI Transmit Interrupt flag. A logic 1 indicates that transmit buffer (SBUF) is empty.This flag must be cleared by software.RI Receive Interrupt flag. A logic 1 indicates that data has been received in thereceive buffer (SBUF). This flag must be cleared by software.

In the example programs the serial port is initialised for mode 3 operation with thereceiver enabled using the following instruction:

MOV SCON, #11010000B

SETTING THE BAUD RATE

Timer/Counter 1 (in SCON mode 3) provides the serial port baud rate clock. Usuallythe 8-bit auto reload operation (Timer/Counter mode 2) is used. The table shows somevalues defined for the TH1 register to achieve some of the more common baud rates.The values shown assume a processor clock rate of 11.059MHz. This is a commoncrystal value for 8051 based designs as it divides down to provide accurate baud rates.

Baud rate Timer/Counter1TH1 value

PCON.7SMOD

8051clock Frequency(inMHz)

300 A0h 0 11.0591200 D0h 0 11.0592400 FAh 0 11.0599600 FDh 0 11.059

Based on the above we could set up the timer for 9,600 baud operation using thefollowing code:

MOV TMOD, #00100000B ; timer/counter 1 set for mode 2, 8-bit TIMER operationMOV TH1, #0FDh ; timer/counter 1 is timed for 9600 baudSETB TR1 ; timer/counter 1 is enabled and will just free run now

Page 55: Introduction to embeded system

P89V51RD28-bit 80C51 5 V low power 64 kB Flash microcontroller with 1 kB RAM

General description

The P89V51RD2 is an 80C51 microcontroller with 64 kB Flash and 1024 bytes ofdata RAM.

A key feature of the P89V51RD2 is its X2 mode option. The design engineer canchoose to run the application with the conventional 80C51 clock rate (12 clocks permachine cycle) or select the X2 mode (6 clocks per machine cycle) to achieve twicethe throughput at the same clock frequency. Another way to benefit from this featureis to keep the same performance by reducing the clock frequency by half, thusdramatically reducing the EMI.

The Flash program memory supports both parallel programming and in serialIn-System Programming (ISP). Parallel programming mode offers gang-programmingat high speed, reducing programming costs and time to market. ISP allows a deviceto be reprogrammed in the end product under software control. The capability tofield/update the application firmware makes a wide range of applications possible.

The P89V51RD2 is also In-Application Programmable (IAP), allowing the Flashprogram memory to be reconfigured even while the application is running.

Page 56: Introduction to embeded system

Features

80C51 Central Processing Unit5 V Operating voltage from 0 to 40 MHz64 kB of on-chip Flash program memory with ISP (In-System Programming) andIAP (In-Application Programming)Supports 12-clock (default) or 6-clock mode selection via software or ISPSPI (Serial Peripheral Interface) and enhanced UARTPCA (Programmable Counter Array) with PWM and Capture/Compare functionsFour 8-bit I/O ports with three high-current Port 1 pins (16 mA each)Three 16-bit timers/countersProgrammable Watchdog timer (WDT)Eight interrupt sources with four priority levelsSecond DPTR registerLow EMI mode (ALE inhibit)TTL- and CMOS-compatible logic levelsBrown-out detectionLow power modesPower-down mode with external interrupt wake-upIdle modePDIP40, PLCC44 and TQFP44 packages