You are on page 1of 98

1

INTRODUCTION

INTRODUCTION TO PROJECT:
OBJECTIVE OF PROJECT:
To observe and take the values of the heart beat and temperature of the patient with minimal time and maximum accuracy.

PROJECT ANALYSIS:
PURPOSE:
Main Problems in the existing system are Slow process and error prone Less secure and causes redundancy of data

So the main purpose of biometric based system is to reduce the effort, time and errors in the existing manual system and get it automated through our software which the work gets completed within fraction of seconds and which is completely free from errors.

PROJECT SCOPE:
Our software automates all works involve small to big hospitails adding the benefit that the work is done within the fraction of seconds. The above facilities will save the time and Productivity of the Institute. Using a heart rate and temperature monitor we can keep track of the heart functionality and body temperature and most of us are aware of the importance of getting enough cardiovascular exercise so every GYM centre will go for one of it.

SPECIFICATIONS:
SOFTWARE: ORKAD and NXP are the schematic design software used as soft ware in micro contriller programming. HARDWARE: When we are working with microcontroller we must keep in mind three things. a. Power supply. b. Crystal. c. Reset.

Power supply: LM7805 regulator is used convert 12V to 5V 3rd pin of LM565 is connected to
40th pin of microcontroller and 2nd pin of LM565 is connected to 20th pin of microcontroller.

Crystal: microcontroller has on chip oscillator. To run that oscillator we must have a external
clock which is provided by crystal. Actually microcontroller supports 10 to 40MHz. Of crystal but we use 11.0592MHz.and 99600 band rate is et to synchronize microcontroller and system.

Reset: this is used to create all the past values and get started again.

SYSTEM REQUIREMENTS:
SOFTWARE REQUIREMENTS:
ORKAD AND NXP SOFTWARE MID Simulation software

HARDWARE REQUIREMENTS:

Microcontroller (P89C51). Analog To Digital Converter. LCD Display

BLOCK DIAGRAM

HEART RATE AND TEMPERATURE MONITORING SYSTEM

ADC P89C51 MICRO CONTROLLER

LCD Display

Regulated power supply

BLOCK DIAGRAM DESCRIPTION


Block diagram comprises of Microcontroller, heart beat sensor, temperature sensor, regulated power supply, LCD display, ADC (analog to digital converter) The heart beat and temperature sensor are interfaced to microcontroller via port pins . Heart beat rate is produced from the LM358 op-amp temperature rate produced by LM35 is fed to microcontroller via ADC(analog to digital converter). An LCD is used to display the sensed data. Most digital logic circuits and processors need a 5 volt power supply. To use these parts we need to build a regulated 5 volt source. Usually you start with an unregulated power To make a 5 volt power supply, we use a LM7805 voltage regulator IC (Integrated Circuit).

IMPLEMENTATION
An embedded system is developed for multiparameter acquisition system. This is an application specific project which can be used universally in hospitals to sense the heart beat and temperature rate Heart beat is sensed using an LM358 op-amp which has an inbuilt amplifier and comparator. An LED and LDR is connected to the heart beat sensor as the heart beat is sensed by taking blood flow into consideration ie a persons heart rate falls down if his /her blood flow is low. Therefore an Led and LDR are used, person whose blood flow is been testing has to place his finger between the LED and ldr. if the blood flow is low the light emmiting from the LED directly falls on the LDR this LDR voltage is fed to the LM358 opamp which is processed and produces the output in the form of pulses at pin number 7 which is further fed to the microcontroller.the microcontroller accepts this input counts either number of ones or zeroes with respect to the code implemented and then displays the number of pulses on the LCD which is the persons heart rate

7
Similarly temperature is sensed using LM35 IC and fed to the microcontroller via ADC . the sensed data is the voltage which is compared to the reference voltage inbuilt in the ADC, suppose resulted greater than the reference voltage 1 is the output of the ADC and vice versa, if equal previous output is considered as the output of ADC.

PROJECT CIRCUITRY

10

CIRCUIT EXPLANATION
The project is divided into four parts like micro controller section, power supply section, heart beat and temperature monitoring section and D.C. regulated power supply section. The Circuit shows the complete diagram of the biometric based heart beat and temperature monitoring system Micro controller section contains only micro controller P89C51 and a crystal of 11.0592 MHz for oscillator. As micro controller works on the program inside the memory.

The heart beat monitoring system consists of lm358 which is in turn connected to an LDR and LED, led is connected to the 8 pin and ldr is connected to 3 pin of lm358.the voltage across the LDR is given to the amplifier as in the above figure the other input to the comparator is nothing but the reference voltage, the two voltages ie the ldr and the reference voltage is compared if equal,pulses are generated at the output of comparator at pin 7 The output of the lm358 at pin 7 is given to any ports of microcontroller ,it counts number of pulses ie either in terms of 1 or 0 and displays the number of pulses on the lcd,which is connected to (PORT O) P0 pins of microcontroller.,the microcontroller internally has a timer which is set for 1 min so that number of pulses counted in 1 minute are recorded

Power supply is an important part of operation of the Microcontroller. Microcontroller operates at +5v DC and also does ICs and display

11

INTRODUCTION TO SENSORS
Introduction:
A sensor is a device that produces a measurable response to a change in a physical condition, such as temperature or thermal conductivity, or to a change in chemical concentration. Sensors are particularly useful for making in-situ measurements such as in industrial process control. Sensors are an important part to any measurement and automation application. The sensor is responsible for converting some type of physical phenomenon into a quantity measurable by a data acquisition (DAQ) system. Choosing a Sensor: Factors to consider when choosing a sensor:

Accuracy - The statistical variance about the exact reading. Calibration - Required for most measuring systems since their readings will drift over time. Environmental - Sensors typically have temperature and/or humidity limits. Range - Limits of measurement or the sensor. Repeatability - The variance in a sensor's reading when a single condition is repeatedly measured. Resolution - The smallest increment the sensor can detect.

12

HEART BEAT SENSOR:


Heart beat sensor (LM358) which is an low power dual op amp The LM358 consists of two independent, high gain, internally frequency compensated operational amplifiers which were designed specifically to operate from a single power supply over a wide range of voltages. Advantages of Two internally compensated op amps n Eliminates need for dual supplies. For example, the LM358 can be directly operated off of the standard +5V power supply voltage which is used in digital systems and will easily provide the required interface electronics without requiring the additional 15V power supplies.

PIN DIAGRAM

13

OPERATION of LM358
The heart beat monitoring system consists of lm358 which is in turn connected to an LDR and LED. LM 358 includes two stages an amplifier and a comparator stage. The amplifier here increases the level of the signal and the comparator is used to compare the LDR voltage to the reference voltage inbuilt in the IC. Led is connected to the 8 pin and ldr is connected to 3 pin of lm358.the voltage across the LDR is given to the amplifier as in the above figure the other input to the comparator is nothing but the reference voltage, the two voltages ie the ldr and the reference voltage is compared if equal, the output at the comparator is same as the input, pulses are generated at the output of comparator at pin 7 The output of the lm358 at pin 7 is given to microcontroller ,it counts number of pulses ie either in terms of 1 or 0 and displays the number of pulses on the lcd, which is connected to any port pins of microcontroller .for instance if the number of pulses are 70, it will display 70 on the lcd which would be the heart beat rate of a person.the microcontroller internally has a timer which is set for 1 min so that number of pulses counted in 1 minute are recorded

TEMPERATURE SENSOR
The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration The LM35's low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 mA from its supply, it has very low self-heating The LM35 is rated to operate over a b55 to a150C temperature range, The LM35 series is available packaged in hermetic TO-46 transistor packages, while the LM35C, LM35CA, and LM35D are also available in the plastic TO-92 transistor package.

14
The LM35D is also available in an 8-lead surface mount small outline package and a plastic TO-202 package. The project code calculates the temperature in Fahrenheit and generates both Centigrade and Fahrenheit outputs to the serial port.

PIN DIAGRAM OF LM 35

It is basically a temperature sensor which is an 8 pin IC when a person touch this sensor,his temperature is recorded and converted to digital form using ADC since the microcontroller accepts only digital input An interesting application for the ADC is to digitize the output of a temperature sensor. One easyto-use temperature sensor is the LM35. The LM35 puts out a voltage proportional to temperature. There are several models of this, but the most common one measures temperatures between 0 and 100C by producing an output voltage 10 mV times the temperature in degrees celcius. Thus a temperature of 20C would be 20 mV. The device has three terminals 5V, ground and output as shown in the diagram. The output of ADC is given to the microcontroller, which reads the temperature and displays on the lc

15

EMBEDDED SYSTEMS

16

EMBEDDED SYSTEM
An embedded system is a special-purpose computer system designed to perform one or a few dedicated functions. It is usually embedded as part of a complete device including hardware and mechanical parts. In contrast, a general-purpose computer, such as a personal computer, can do many different tasks depending on programming. Embedded systems have become very important today, as they control many of the common devices we use. Since the embedded system is dedicated to specific tasks, design engineers can optimize it, reducing the size and cost of the product, or increasing the reliability and performance. 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 an exactly defined term, as many systems have some element of programmability. For example, Handheld computers share some elements with embedded systems such as the operating systems and microprocessors which power them but are not truly embedded systems, because they allow different applications to be loaded and peripherals to be connected. An embedded system is some combination of computer hardware and software, either fixed in capability or programmable, that is specifically designed for a particular kind of application device. Industrial machines, automobiles, medical equipment, cameras, household appliances, airplanes, vending machines, and toys (as well as the more obvious cellular phone and PDA) are among the myriad possible hosts of an embedded system. Embedded systems that are programmable are provided with a programming interface, and embedded systems programming is a specialized occupation. Certain operating systems or language platforms are tailored for the embedded market, such as Embedded Java and Windows XP Embedded. However, some low-end consumer products use very inexpensive microprocessors and limited storage, with the application and operating system

17
both part of a single program. The program is written permanently into the system's memory in this case, rather than being loaded into RAM (random access memory), as programs on a personal computer are.

INTRODUCTION TO EMBEDDED SYSTEM


We are living in the Embedded World. You are surrounded with many embedded products and your daily life largely depends on the proper functioning of these gadgets. Television, Radio, CD player of your living room, Washing Machine or Microwave Oven in your kitchen, Card readers, Access Controllers, Palm devices of your work space enable you to do many of your tasks very effectively. Apart from all these, many controllers embedded in your car take care of car operations between the bumpers and most of the times you tend to ignore all these controllers. In recent days, you are showered with variety of information about these embedded controllers in many places. All kinds of magazines and journals regularly dish out details about latest technologies, new devices, fast applications which make you believe that your basic survival is controlled by these embedded products. Now you can agree to the fact that these embedded products have successfully invaded into our world. You must be wondering about these embedded controllers or systems. What is this Embedded System? The computer you use to compose your mails, or create a document or analyze the database is known as the standard desktop computer. These desktop computers are manufactured to serve many purposes and applications. You need to install the relevant software to get the required processing facility. So, these desktop computers can do many things. In contrast, embedded controllers carryout a specific work for which they are designed. Most of the time, engineers design these embedded controllers with a specific goal in mind. So these controllers cannot be used in any other place. Theoretically, an embedded controller is a combination of a piece of microprocessor based hardware and the suitable software to undertake a specific task. These days designers have many choices in microprocessors/microcontrollers. Especially, in 8 bit and 32 bit, the available variety really may overwhelm even an experienced designer. Selecting a right microprocessor may turn out as a most difficult first step and it is getting complicated as new devices continue to pop-up very often.

18
In the 8 bit segment, the most popular and used architecture is Intel's 8031. Market acceptance of this particular family has driven many semiconductor manufacturers to develop something new based on this particular architecture. Even after 25 years of existence, semiconductor manufacturers still come out with some kind of device using this 8031 core.

MICROCONTROLLER Micro controllers:


The first microprocessor introduced in 1971, was made possible by high levels of integration of digital circuits. Continued integration of peripherals and memory on the same integrated circuit as the microprocessor core led to the creation of micro controllers. A micro controller is an integrated circuit composed of a CPU, various peripheral devices, and typically memory, all in one chip. Using one chip that contains all the necessary functions in place of a microprocessor and multiple peripheral chips has reduced the size and the power consumption of control oriented applications. A micro controller is different from a microprocessor both in hardware and software. In hardware it includes peripherals such as I/O, memory, and analog and digital interface. Micro controllers are more suited for small applications with specific control functions requiring specialized peripherals and interfaces. They are designed for process control and are required to interface to the real world processes. Many of the peripheral devices integrated on a micro controller are for that specific purpose. Analog to digital converters perform the task of converting an analog signal to digital for use by the CPU, and digital to analog converters perform the task of converting digital data into analog value and waveforms to control analog functions. In addition to the analog interface, micro controllers contain peripheral devices that enable them to communicate to other digital components within a system or to monitor and control digital functions. Communication interfaces, digital I/O and interrupt controllers fall into this category of peripheral devices. Other peripheral devices often included on the same chip include clocks and timers. Micro-controllers are used in a variety of process control applications, replacing complex digital circuits and sometimes-analog functions while providing more flexibility due to their programmability. Portable electronic devices such as personal audio devices (CD players, MP3 players), mobile telephones, digital cameras and video camcorders rely heavily on the reduced size and low power consumption of micro controller based electronics. These features are crucial to applications like implantable medical devices such as pacemakers, or personal medical monitoring devices like glucometers (electronic devices used for the measurement of blood

19
glucose). In other applications such as appliances, home audio and video, automotive, power management, and temperature control, using a micro controller results in reduced board level circuit complexity and consequently reduced cost. With the growing number of applications using micro controllers, it is not surprising that there are such a wide variety of these components. In addition to those commonly available, many manufacturers custom-design a micro controller to suit a specific application.

MICROCONTROLLERS FOR EMBEDDED SYSTEMS


In the Literature discussing microprocessors, we often see the term Embedded System. Microprocessors and Microcontrollers are widely used in embedded system products. An embedded system product uses a microprocessor (or Microcontroller) to do one task only. A printer is an example of embedded system since the processor inside it performs one task only; namely getting the data and printing it. Contrast this with a Pentium based PC. A PC can be used for any number of applications such as word processor, print-server, bank teller terminal, Video game, network server, or Internet terminal. Software for a variety of applications can be loaded and run. of course the reason a pc can perform myriad tasks is that it has RAM memory and an operating system that loads the application software into RAM memory and lets the CPU run it. In an Embedded system, there is only one application software that is typically burned into ROM. An x86 PC contains or is connected to various embedded products such as keyboard, printer, modem, disk controller, sound card, CD-ROM drives, mouse, and so on. Each one of these peripherals has a Microcontroller inside it that performs only one task. For example, inside every mouse there is a Microcontroller to perform the task of finding the mouse position and sending it to the PC..

20

MICROCONTROLLER

21

Micro processors vs Micro controllers:


The prime use of a microprocessor is to read data, perform extensive calculations on that data, and store those calculations in a mass storage device or display the results. The programs used by the microprocessor are stored in the mass storage device and loaded into RAM as user directs. A few microprocessor programs are stored in ROM. The ROM based programs are primarily small fixed programs that operate peripherals and other fixed devices that are connected to the system. The block diagram of typical microcontroller, which is a true computer on a chip, is as shown in figure. The design incorporates all the features found in a micro-processor CPU: ALU, PC, SP, and registers. It also has added the other features needed to make a complete computer: ROM, RAM, parallel I/O, serial I/O, counters and a clock circuit. Like the microprocessor, a microcontroller is a general-purpose device, but one that is meant to read data, performs limited calculations on that data, and control its environment based on those calculations. The prime use of a microcontroller is to control the operation of a machine using a fixed program that is stored on ROM and that does not change over the lifetime if the system. The contrast between a microcontroller and a microprocessor is best exemplified by the fact that most microprocessors have many operational codes (op-codes) for moving data from external memory to CPU; microcontrollers may have one or two. Microcontroller may have one or two types of bit-handling instructions; microprocessor will have many.

NECESSITY OF MICROCONTROLLERS:
Microprocessors brought the concept of programmable devices and made many applications of intelligent equipment. Most applications, which do not need large amount of data and program memory.

22
The microprocessor system had to satisfy the data and program requirements so; sufficient RAM and ROM are used to satisfy most applications .The peripheral control equipment also had to be satisfied. Therefore, almost all-peripheral chips were used in the design. Because of these additional peripherals cost will be comparatively high. Why only Philips? The 89C51RD2 device contains a non-volatile 64kB Flash program memory that is both parallel programmable and serial In-System and In-Application Programmable. In-System Programming (ISP) allows the user to download new code while the microcontroller sits in the application. In-Application Programming (IAP) means that the microcontroller fetches new program code and reprograms itself while in the system. This allows for remote programming over a modem link. A default serial loader (boot loader) program in ROM allows serial In-System programming of the Flash memory via the UART without the need for a loader in the Flash code. For In-Application Programming, the user program erases and reprograms the Flash memory by use of standard routines contained in ROM.

Architecture
Architecturally all micro controllers share certain features. They all contain a CPU, memory and I/O on the same chip. Another common feature is the interrupt handling capability. What sets them apart from one another is the choice of CPU, the structure of memory, and choice of peripheral devices, I/O and interrupts handling hardware. The major distinguishing architectural characteristic of micro controllers is the word size. Micro-controllers are available in 4, 8, 16, or 32 bit wide words. The width of the data path impacts several features of the micro controller. The complexity of the instruction set (number of available instructions and addressing modes), program efficiency (code generation and storage space), execution speed, as well as chip implementation and interfacing complexity are all influenced by the width of the data path. For simple control tasks 4-bit, and for a vast number of control and measurement applications 8-bit micro controllers would be sufficient. For higher precision and speed applications like speech and video processing, or complex instrumentation, 16-bit and 32-bit micro controllers are more appropriate. Another distinction between micro controllers is the instruction set. Micro-controllers with complex instruction set (CISC) provide capability to perform complex computations rapidly. The extensive set of instructions, allow complex operations to be performed with few instructions. On the other hand reduced instruction set computers (RISC) decrease program execution time by having fewer less complex instructions. Fewer available instructions results in faster execution

23
due to smaller size of the op-code and less decoding time needed for each instruction. The tradeoff depends on the complexity of operations needed for a specific application. In simple control applications a RISC based micro controller is more suitable because of its lower overhead for each instruction. In more complex applications, the availability of a more diverse instruction set results in a more efficient and faster executing code because fewer instructions are needed to accomplish a complicated task. For micro controller applications the instruction set should include common computational instructions plus instructions optimized for the specific application at hand. Just as in microprocessors, micro controllers are also differentiated according to their memory structure. Von Neumann architecture maps the data and program to same memory address space. In the Harvard architecture the instructions are stored in a separate memory space than that used for data storage. Another memory related architectural characteristic of a processor is the addressing scheme. In linear addressing there is a one to one correspondence between an address and a memory location. So with an 8-bit address register, 2 8 distinct address locations can be accessed. In segmented addressing a separate register is used to point to a segment in memory, and the address register is used to point to an offset from that segments start point. This way if all of the program or data are in the same segment, in order to access them, only the address register need to be used and the segment register can remain pointing to the start point of that segment. Widely used group of micro controllers is Intels MCS51 family. These micro controllers are also 8-bit processors, but with a separate 64Kbyte of data and 64Kbyte of program memory space. As implied by this statement, devices in the MCS51 utilize Harvard architecture. All of I/O addresses as well as CPU registers and various peripheral devices registers are mapped in the same space as the data. The 8051, which is one of the options in this family, has 5 interrupt sources, 2 external, two timer interrupts and one serial port interrupt. Interrupt priority is resolved through a priority scheme and ranking in the polling sequence. The priority scheme allows each interrupt to be programmed to one of two priority levels. Furthermore if two interrupts with the same priority occur simultaneously, they are serviced based on their rank in the polling sequence. Other manufacturers such as AMD, Dallas Semiconductor, Fujitsu and Philips also supply micro controllers in the MCS51 family. Dallas Semiconductors DC87C550 provides increased performance over Intels 8051 while maintaining instruction set compatibility. Many instructions that execute in 12 CPU clock cycles in an 8051, will execute in only 4 clocks for the DC87C550 therefore resulting in increased execution speeds of up to three times. Additionally, the DC87C550 has a power management mode that allows slowing of the processor in order to

24
reduce power consumption. This mode can be utilized in battery operated or otherwise low power applications. The architecture of the instruction set varies greatly from one micro controller to another. The choices made in designing the instruction set impact program memory space usage, code execution speed, and ease of programming. Prioritize interrupts; interrupt handling hardware is often included on the micro controller chip. Interrupt handlers usually provide multiple interrupt inputs, with different levels of priority and the means to mask certain interrupts. An example of interrupts is power failure in a hand held thermometer. Should the battery voltage drop below acceptable limits at any time, the device should inform the user of the condition and possibly perform preventive measures before returning control to the interrupted program. 8051 DERIVATIVES Along the way, this 8031 architecture gained enviable market acceptance. Many semiconductor manufacturers started either manufacturing the 8031 devices as such (Intel was liberal in giving away license to whoever asked) or developing a new kind of microcontrollers based on 8031 core architecture.Manufacturers modified the basic 8031 architecture and added many new peripheral functions to make them attractive to the designers.

Because of the rush, electronic community started getting a variety of 8031 based devices with range of options. To beat the competition, manufacturers developed different microcontrollers with many unique features. These parts are popularly known as '8031 Derivatives'. Almost every decent manufacturer boasted of having an 8031 based microcontroller in the line card. First major manufacturer was the Philips who brought out more than 40-50 derivatives with a variety of I/O options, memory combinations, and peripheral functions. Devices became available in regular DIP and SMD packages. With the basic 8031 core, Philips ported high capacity Program Memory (upto 32K/64K), its patented I2C interface bus, 8/10 bit Analog to Digital Converters, CAN Bus, Capture and Compare registers, Watch dog timer, PWM facilities and etc. More I/O ports (as many as eight ports), additional timer/counter, second serial port was also made available in Philips devices.

25
Apart from all these, Philips developed many consumer devices meant for telecom, computer and TV applications. A smart card controller was also developed by incorporating a cryptographic engine. So Philips clearly established itself as the market leader in 8031 derivatives and still caters to this segment. Dallas semiconductor also has got a range of secure microcontrollers based on 8031 core. This microcontroller family uses non volatile RAM to keep both program and data. Because of this RAM, the controller gives the In System Reprogrammability. Dallas has combined this microcontroller, SRAM and lithium cell in a single pack. This device guarantees 10+ years of data retention in the RAM area. This 8031 also boasts the tamper proof security features like Real Time Memory Encryption, user selected 48 bit Encryption key, memory contents, security lock and the facility to hide interrupt vector table. As you can agree, this particular 8031 device has found a niche market in banking and security related applications. Meantime, Intel itself tried to cash in the popularity of this 8031 architecture and introduced improved versions of microcontrollers: 80151 and 80251 families. These devices sport 16 bit architecture using 8031 core and unfortunately these devices have not become as popular as 8031.Even after many years of introduction, 8031 core is still going strong in 8 bit arena.

26

PHILIPS MICROCONTROLLER
DESCRIPTION:

The Philips microcontrollers described in this data sheet are high-performance static 80C51 designs. They are manufactured in an advanced CMOS process and contain a non-volatile Flash program memory. They support both 12-clock and 6-clock operation. The P89C51X2 and P89C52X2/54X2/58X2 contain 128 byte RAM and 256 byte RAM respectively, 32 I/O lines, three 16-bit counter/timers, a six-source, four-priority level nested interrupt structure, a serial I/O port for either multi-processor communications, I/O expansion or full duplex UART, and on-chip oscillator and clock circuits. In addition, the devices are static designs which offer a wide range of operating frequencies down to zero. Two software selectable modes of power reduction idle mode and power-down mode are available. The idle mode freezes the CPU while allowing the RAM, timers, serial port, and interrupt system to continue functioning. The power-down mode saves the RAM contents but freezes the oscillator, causing all other chip functions to be in operative. Since the design is static, the clock can be stopped without loss of user data. Then the execution can be resumed from the point the clock was stopped.

27

NOTE: 1. I2C = Inter-Integrated Circuit Bus; CAN = Controller Area Network; SPI = Serial Peripheral Interface; PCA = Programmable Counter Array; ADC = Analog-to-Digital Converter; PWM = Pulse Width Modulation

28

FEATURES
BLOCK DIAGRAM

RESET
A reset is accomplished by holding the RST pin HIGH for at least two machine cycles (24 oscillator periods in 12-clock and 12 oscillator periods in 6-clock mode), while the oscillator is running. To insure a reliable power-up reset, the RST pin must be high long enough to allow the oscillator time to start up (normally a few milliseconds) plus two machine cycles, unless it has been set to 6-clock operation using a parallel programmer.

LOW POWER MODES

29 Stop Clock Mode:


The static design enables the clock speed to be reduced down to 0 MHz (stopped). When the oscillator is stopped, the RAM and Special Function Registers retain their values. This mode allows step-by-step utilization and permits reduced system power consumption by lowering the clock frequency down to any value. For lowest power consumption the Power Down mode is suggested.

Idle Mode
In idle mode (see Table 3), the CPU puts itself to sleep while all of the on-chip peripherals stay active. The instruction to invoke the idle mode is the last instruction executed in the normal operating mode before the idle mode is activated. The CPU contents, the on-chip RAM, and all of the special function registers remain intact during this mode. The idle mode can be terminated either by any enabled interrupt (at which time the process is picked up at the interrupt service routine and continued), or by a hardware reset which starts the processor in the same manner as a power-on reset.

Power-Down Mode
To save even more power, a Power Down mode (see Table 3) can be invoked by software. In this mode, the oscillator is stopped and the instruction that invoked Power Down is the last instruction executed. The on-chip RAM and Special Function Registers retain their values down to 2.0 V and care must be taken to return VCC to the minimum specified operating voltages before the Power Down Mode is terminated. Either a hardware reset or external interrupt can be used to exit from Power Down. Reset redefines all the SFRs but does not change the on-chip RAM. An external interrupt allows both the SFRs and the on-chip RAM to retain their values. WUPD (AUXR1.3Wakeup from Power Down) enables or disables the wakeup from power down with external interrupt. Where: WUPD = 0: Disable WUPD = 1: Enable To properly terminate Power Down, the reset or external interrupt should not be executed before VCC is restored to its normal operating level and must be held active long enough for the oscillator to restart and stabilize (normally less than 10 ms).

30
To terminate Power Down with an external interrupt, INT0 or INT1 must be enabled and configured as level-sensitive. Holding the pin low restarts the oscillator but bringing the pin back high completes the exit. Once the interrupt is serviced, the next instruction to be executed after RETI will be the one following the instruction that put the device into Power Down.

Design Consideration
When the idle mode is terminated by a hardware reset, the device normally resumes program execution from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhibits access to internal RAM in this event, but access to the port pins is not inhibited. To eliminate the possibility of an unexpected write when Idle is terminated by reset, the instruction following the one that invokes Idle should not be one that writes to a port pin or to external memory.

ONCE Mode
The ONCE (On-Circuit Emulation) Mode facilitates testing and debugging of systems without the device having to be removed from the circuit. The ONCE Mode is invoked in the following way: 1. Pull ALE low while the device is in reset and PSEN is high; 2. Hold ALE low as RST is deactivated. While the device is in ONCE Mode, the Port 0 pins go into a float state, and the other port pins and ALE and PSEN are weakly pulled high. The oscillator circuit remains active. While the device is in this mode, an emulator or test CPU can be used to drive the circuit. Normal operation is restored when a normal reset is applied.

31

TIMER 0 AND TIMER 1 OPERATION Timer 0 and Timer 1


The Timer or Counter function is selected by control bits C/T in the Special Function Register TMOD. These two Timer/Counters have four operating modes, which are selected by bit-pairs (M1, M0) in TMOD. Modes 0, 1, and 2 are the same for both Timers/Counters. Mode 3 is different. The four operating modes are described in the following text.

Mode 0
Putting either Timer into Mode 0 makes it look like an 8048 Timer, which is an 8-bit Counter with a divide-by-32 prescaler. Figure 2 shows the Mode 0 operation. In this mode, the Timer register is configured as a 13-bit register. As the count rolls over from all 1s to all 0s, it sets the Timer interrupt flag TFn. The counted input is enabled to the Timer when TRn = 1 and either GATE = 0 or INTn = 1. (Setting GATE = 1 allows the Timer to be controlled by external input INTn, to facilitate pulse width measurements). TRn is a control bit in the Special Function Register TCON (Figure 3). The 13-bit register consists of all 8 bits of THn and the lower 5 bits of TLn. The upper 3 bits of TLn are indeterminate and should be ignored. Setting the run flag (TRn) does not clear the registers. Mode 0 operation is the same for Timer 0 as for Timer 1. There are two different GATE bits, one for Timer 1 (TMOD.7) and one for Timer 0 (TMOD.3).

Mode 1
Mode 1 is the same as Mode 0, except that the Timer register is being run with all 16 bits.

Mode 2
Mode 2 configures the Timer register as an 8-bit Counter (TLn) with automatic reload, as shown in Figure 4. Overflow from TLn not only sets TFn, but also reloads TLn with the contents of THn, which is preset by software. The reload leaves THn unchanged. Mode 2 operation is the same for Timer 0 as for Timer 1.

Mode 3
Timer 1 in Mode 3 simply holds its count. The effect is the same as setting TR1 = 0. Timer 0 in Mode 3 establishes TL0 and TH0 as two separate counters. The logic for Mode 3 on Timer 0 is

32
shown in Figure 5. TL0 uses the Timer 0 control bits: C/T, GATE, TR0, and TF0 as well as pin INT0. TH0 is locked into a timer function (counting machine cycles) and takes over the use of TR1 and TF1 from Timer 1. Thus, TH0 now controls the Timer 1 interrupt.

33

TIMER 2 OPERATION
Timer 2
Timer 2 is a 16-bit Timer/Counter which can operate as either an event timer or an event counter, as selected by C/T2 in the special function register T2CON (see Figure 6). Timer 2 has three

34
operating modes: Capture, Auto-reload (up or down counting), and Baud Rate Generator, which are selected by bits in the T2CON as shown in Table 4.

Auto-Reload Mode (Up or Down Counter)


In the 16-bit auto-reload mode, Timer 2 can be configured as either a timer or counter (C/T2 in T2CON), then programmed to count up or down. The counting direction is determined by bit DCEN (Down Counter Enable) which is located in the T2MOD register (see Figure 8). After reset, DCEN=0 which means Timer 2 will default to counting up. If DCEN is set, Timer 2 can count up or down depending on the value of the T2EX pin. Figure 9 shows Timer 2 which will count up automatically since DCEN=0. In this mode there are two options selected by bit EXEN2 in T2CON register. If EXEN2=0, then Timer 2 counts up to 0FFFFH and sets the TF2 (Overflow Flag) bit upon overflow. This causes the Timer 2 registers to be reloaded with the 16-bit value in RCAP2L and RCAP2H. The values in RCAP2L and RCAP2H are preset by software. If EXEN2=1, then a 16-bit reload can be triggered either by an overflow or by a 1-to-0 transition at input T2EX. This transition also sets the EXF2 bit. The Timer 2 interrupt, if enabled, can be generated when either TF2 or EXF2 are 1. In Figure 10 DCEN=1 which enables Timer 2 to count up or down. This mode allows pin T2EX to control the direction of count. When logic 1 is applied at pin T2EX, Timer 2 will count up. Timer 2 will overflow at 0FFFFH and set the TF2 flag, which can then generate an interrupt, if the interrupt is enabled. This timer overflow also causes the 16-bit value in RCAP2L and RCAP2H to be reloaded into the timer registers TL2 and TH2. A logic 0 applied to pin T2EX causes Timer 2 to count down. The timer will underflow when TL2 and TH2 become equal to the value stored in RCAP2L and RCAP2H. A Timer 2 underflow sets the TF2 flag and causes 0FFFFH to be reloaded into the timer registers TL2 and TH2. The external flag EXF2 toggles when Timer 2 underflows or overflows. This EXF2 bit can be used as a 17th bit of resolution if needed. The EXF2 flag does not generate an interrupt in this mode of operation.

Baud Rate Generator Mode

35
Bits TCLK and/or RCLK in T2CON (Table 4) allow the serial port transmit and receive baud rates to be derived from either Timer 1 or Timer 2. When TCLK= 0, Timer 1 is used as the serial port transmit baud rate generator. When TCLK= 1, Timer 2 is used as the serial port transmit baud rate generator. RCLK has the same effect for the serial port receive baud rate. With these two bits, the serial port can have different receive and transmit baud rates one generated by Timer 1, the other by Timer 2. Figure 11 shows the Timer 2 in baud rate generation mode. The baud rate generation mode is like the auto-reload mode, in that a rollover in TH2 causes the Timer 2 registers to be reloaded with the 16-bit value in registers RCAP2H and RCAP2L, which are preset by software. The baud rates in modes 1 and 3 are determined by Timer 2s overflow rate given below: Modes 1 and 3 Baud Rates _ Timer 2 Overflow Rate 16 The timer can be configured for either timer or counter operation. In many applications, it is configured for timer operation (C/T2=0). Timer operation is different for Timer 2 when it is being used as a baud rate generator. Usually, as a timer it would increment every machine cycle (i.e., 1/6 the oscillator frequency in 6clock mode or 1/12 the oscillator frequency in 12-clock mode). As a baud rate generator, it increments at the oscillator frequency in 6-clock mode or at 1/2 the oscillator frequency in 12clock mode. Thus the baud rate formula is as follows:

Where: n = 16 in 6-clock mode, 32 in 12-clock mode. (RCAP2H, RCAP2L)= The content of RCAP2H and RCAP2L taken as a 16-bit unsigned integer. The Timer 2 as a baud rate generator mode shown in Figure 11 is valid only if RCLK and/or TCLK = 1 in T2CON register. Note that a rollover in TH2 does not set TF2, and will not generate an interrupt. Thus, the Timer 2 interrupt does not have to be disabled when Timer 2 is in the baud rate generator mode. Also if the EXEN2 (T2 external enable flag) is set, a 1-to-0 transition in T2EX (Timer/counter 2 trigger input) will set EXF2 (T2 external flag) but will not cause a reload from (RCAP2H, RCAP2L) to (TH2,TL2). Therefore when Timer 2 is in use as a baud rate generator,

36
T2EX can be used as an additional external interrupt, if needed. When Timer 2 is in the baud rate generator mode, one should not try to read or write TH2 and TL2. As a baud rate generator, Timer 2 is incremented every state time (osc/2) or asynchronously from pin T2; under these conditions, a read or write of TH2 or TL2 may not be accurate. The RCAP2 registers may be read, but should not be written to, because a write might overlap a reload and cause write and/or reload errors. The timer should be turned off (clear TR2) before accessing the Timer 2 or RCAP2 registers. Table 5 shows commonly used baud rates and how they can be obtained from Timer 2. .

Summary Of Baud Rate Equations Timer 2 is in baud rate generating mode. If Timer 2 is being clocked through pin T2(P1.0) the baud rate is:

If Timer 2 is being clocked internally, the baud rate is:

Where: n = 16 in 6-clock mode, 32 in 12-clock mode.

37
fOSC= Oscillator Frequency To obtain the reload value for RCAP2H and RCAP2L, the above equation can be rewritten as:

Timer/Counter 2 Set-up Except for the baud rate generator mode, the values given for T2CON do not include the setting of the TR2 bit. Therefore, bit TR2 must be set, separately, to turn the timer on. See Table 6 for set-up of Timer 2 as a timer. Also see Table 7 for set-up of Timer 2 as a counter.

38

NOTES: 1. Capture/reload occurs only on timer/counter overflow. 2. Capture/reload occurs on timer/counter overflow and a 1-to-0 transition on T2EX (P1.1) pin except when Timer 2 is used in the baud rate generator mode. FULL-DUPLEX ENHANCED UART Standard UART operation The serial port is full duplex, meaning it can transmit and receive simultaneously. It is also receive-buffered, meaning it can commence reception of a second byte before a previously received byte has been read from the register. (However, if the first byte still hasnt been read by the time reception of the second byte is complete, one of the bytes will be lost.) The serial port receive and transmit registers are both accessed at Special Function Register SBUF. Writing to SBUF loads the transmit register, and reading SBUF accesses a physically separate receive register. The serial port can operate in 4 modes: Mode 0: Serial data enters and exits through RxD. TxD outputs the shift clock. 8 bits are transmitted/received (LSB first). The baud rate is fixed at 1/12 the oscillator frequency (in 12clock mode) or 1/6 the oscillator frequency (in 6-clock mode). Mode 1: 10 bits are transmitted (through TxD) or received (through RxD): a start bit (0), 8 data bits (LSB first), and a stop bit (1). On receive, the stop bit goes into RB8 in Special Function Register SCON. The baud rate is variable. Mode 2: 11 bits are transmitted (through TxD) or received (through RxD): start bit (0), 8 data bits (LSB first), a programmable 9th data bit, and a stop bit (1). On Transmit, the 9th data bit (TB8 in SCON) can be assigned the value of 0 or 1. Or, for example, the parity bit (P, in the PSW) could be moved into TB8. On receive, the 9th data bit goes into RB8 in Special Function Register SCON, while the stop bit is ignored. The baud rate is programmable to either 1/32 or 1/64 the oscillator frequency (in 12-clock mode) or 1/16 or 1/32 the oscillator frequency (in 6-clock mode).

39
Mode 3: 11 bits are transmitted (through TxD) or received (through RxD): a start bit (0), 8 data bits (LSB first), a programmable 9th data bit, and a stop bit (1). In fact, Mode 3 is the same as Mode 2 in all respects except baud rate. The baud rate in Mode 3 is variable. In all four modes, transmission is initiated by any instruction that uses SBUF as a destination register. Reception is initiated in Mode 0 by the condition RI = 0 and REN = 1. Reception is initiated in the other modes by the incoming start bit if REN = 1. Multiprocessor Communications Modes 2 and 3 have a special provision for multiprocessor communications. In these modes, 9 data bits are received. The 9th one goes into RB8. Then comes a stop bit. The port can be programmed such that when the stop bit is received, the serial port interrupt will be activated only if RB8 = 1. This feature is enabled by setting bit SM2 in SCON. A way to use this feature in multiprocessor systems is as follows: When the master processor wants to transmit a block of data to one of several slaves, it first sends out an address byte which identifies the target slave. An address byte differs from a data byte in that the 9th bit is 1 in an address byte and 0 in a data byte. With SM2 = 1, no slave will be interrupted by a data byte. An address byte, however, will interrupt all slaves, so that each slave can examine the received byte and see if it is being addressed. The addressed slave will clear its SM2 bit and prepare to receive the data bytes that will be coming. The slaves that werent being addressed leave their SM2s set and go on about their business, ignoring the coming data bytes. SM2 has no effect in Mode 0, and in Mode 1 can be used to check the validity of the stop bit. In a Mode 1 reception, if SM2 = 1, the receive interrupt will not be activated unless a valid stop bit is received. Serial Port Control Register The serial port control and status register is the Special Function Register SCON, shown in Figure 12. This register contains not only the mode selection bits, but also the 9th data bit for transmit and receive (TB8 and RB8), and the serial port interrupt bits (TI and RI). Baud Rates The baud rate in Mode 0 is fixed: Mode 0 Baud Rate = Oscillator Frequency / 12 (in 12-clock mode) or / 6 (in 6-clock mode). The baud rate in Mode 2 depends on the value of bit SMOD in Special Function Register PCON. If SMOD = 0 (which is the value on reset), and the port pins in 12-clock mode, the baud rate is 1/64 the oscillator frequency. If SMOD = 1, the baud rate is 1/32 the oscillator frequency. In 6-clock mode, the baud rate is 1/32 or 1/16 the oscillator frequency, respectively.

40

Where: n = 64 in 12-clock mode, 32 in 6-clock mode The baud rates in Modes 1 and 3 are determined by the Timer 1 or Timer 2 overflow rate. Using Timer 1 to Generate Baud Rates When Timer 1 is used as the baud rate generator (T2CON.RCLK = 0, T2CON.TCLK = 0), the baud rates in Modes 1 and 3 are determined by the Timer 1 overflow rate and the value of SMOD as follows:

Where: n = 32 in 12-clock mode, 16 in 6-clock mode The Timer 1 interrupt should be disabled in this application. The Timer itself can be configured for either timer or counter operation, and in any of its 3 running modes. In the most typical applications, it is configured for timer operation, in the auto-reload mode (high nibble of TMOD = 0010B). In that case the baud rate is given by the formula:

Where: n = 32 in 12-clock mode, 16 in 6-clock mode One can achieve very low baud rates with Timer 1 by leaving the Timer 1 interrupt enabled, and configuring the Timer to run as a 16-bit timer (high nibble of TMOD = 0001B), and using the Timer 1 interrupt to do a 16-bit software reload. Figure 13 lists various commonly used baud rates and how they can be obtained from Timer 1. Enhanced UART operation In addition to the standard operation modes, the UART can perform framing error detect by looking for missing stop bits, and automatic address recognition. The UART also fully supports multiprocessor communication.

41
When used for framing error detect the UART looks for missing stop bits in the communication. A missing bit will set the FE bit in the SCON register. The FE bit shares the SCON.7 bit with SM0 and the function of SCON.7 is determined by PCON.6 (SMOD0) (see Figure 18). If SMOD0 is set then SCON.7 functions as FE. SCON.7 functions as SM0 when SMOD0 is cleared. When used as FE SCON.7 can only be cleared by software. Refer to Figure 19. Automatic Address Recognition Automatic Address Recognition is a feature which allows the UART to recognize certain addresses in the serial bit stream by using hardware to make the comparisons. This feature saves a great deal of software overhead by eliminating the need for the software to examine every serial address which passes by the serial port. This feature is enabled by setting the SM2 bit in SCON. In the 9 bit UART modes, mode 2 and mode 3, the Receive Interrupt flag (RI) will be automatically set when the received byte contains either the Given address or the Broadcast address. The 9 bit mode requires that the 9th information bit is a 1 to indicate that the received information is an address and not data. Automatic address recognition is shown in Figure 20. The 8 bit mode is called Mode 1. In this mode the RI flag will be set if SM2 is enabled and the information received has a valid stop bit following the 8 address bits and the information is either a Given or Broadcast address. Mode 0 is the Shift Register mode and SM2 is ignored. Using the Automatic Address Recognition feature allows a master to selectively communicate with one or more slaves by invoking the Given slave address or addresses. All of the slaves may be contacted by using the Broadcast address. Two special Function Registers are used to define the slaves address, SADDR, and the address mask, SADEN. SADEN is used to define which bits in the SADDR are to be used and which bits are dont care. The SADEN mask can be logically ANDed with the SADDR to create the Given address which the master will use for addressing each of the slaves. Use of the Given address allows multiple slaves to be recognized while excluding others. The following examples will help to show the versatility of this scheme: Slave 0 SADDR = 1100 0000 SADEN = 1111 1101 Given = 1100 00X0 Slave 1 SADDR = 1100 0000 SADEN = 1111 1110 Given = 1100 000X

42
In the above example SADDR is the same and the SADEN data is used to differentiate between the two slaves. Slave 0 requires a 0 in bit 0 and it ignores bit 1. Slave 1 requires a 0 in bit 1 and bit 0 is ignored. A unique address for Slave 0 would be 1100 0010 since slave 1 requires a 0 in bit 1. A unique address for slave 1 would be 1100 0001 since a 1 in bit 0 will exclude slave 0. Both slaves can be selected at the same time by an address which has bit 0 = 0 (for slave 0) and bit 1 = 0 (for slave 1). Thus, both could be addressed with 1100 0000. In a more complex system the following could be used to select slaves 1 and 2 while excluding slave 0: Slave 0 SADDR = 1100 0000 SADEN = 1111 1001 Given = 1100 0XX0 Slave 1 SADDR = 1110 0000 SADEN = 1111 1010 Given = 1110 0X0X Slave 2 SADDR = 1110 0000 SADEN = 1111 1100 Given = 1110 00XX In the above example the differentiation among the 3 slaves is in the lower 3 address bits. Slave 0 requires that bit 0 = 0 and it can be uniquely addressed by 1110 0110. Slave 1 requires that bit 1 = 0 and it can be uniquely addressed by 1110 and 0101. Slave 2 requires that bit 2 = 0 and its unique address is 1110 0011. To select Slaves 0 and 1 and exclude Slave 2 use address 1110 0100, since it is necessary to make bit 2 = 1 to exclude slave 2. The Broadcast Address for each slave is created by taking the logical OR of SADDR and SADEN. Zeros in this result are trended as dont-cares. In most cases, interpreting the dont-cares as ones, the broadcast address will be FF hexadecimal. Upon reset SADDR (SFR address 0A9H) and SADEN (SFR address 0B9H) are leaded with 0s. This produces a given address of all dont cares as well as a Broadcast address of all dont cares. This effectively disables the Automatic Addressing mode and allows the microcontroller to use standard 80C51 type UART drivers which do not make use of this feature.

43

Interrupts:

44
The devices described in this data sheet provide six interrupt sources. These are shown in Figure 21. The External Interrupts INT0 and INT1 can each be either level-activated or transition-activated, depending on bits IT0 and IT1 in Register TCON. The flags that actually generate these interrupts are bits IE0 and IE1 in TCON. When an external interrupt is generated, the flag that generated it is cleared by the hardware when the service routine is vectored to only if the interrupt was transition-activated. If the interrupt was level-activated, then the external requesting source is what controls the request flag, rather than the on-chip hardware. The Timer 0 and Timer 1 Interrupts are generated by TF0 and TF1, which are set by a rollover in their respective Timer/Counter registers (except see Timer 0 in Mode 3). When a timer interrupt is generated, the flag that generated it is cleared by the on-chip hardware when the service routine is vectored to. The Serial Port Interrupt is generated by the logical OR of RI and TI. Neither of these flags is cleared by hardware when the service routine is vectored to. In fact, the service routine will normally have to determine whether it was RI or TI that generated the interrupt, and the bit will have to be cleared in software. All of the bits that generate interrupts can be set or cleared by software, with the same result as though it had been set or cleared by hardware. That is, interrupts can be generated or pending interrupts can be canceled in software. Each of these interrupt sources can be individually enabled or disabled by setting or clearing a bit in Special Function Register IE (Figure 22). IE also contains a global disable bit, EA, which disables all interrupts at once.

Priority Level Structure:


Each interrupt source can also be individually programmed to one of four priority levels by setting or clearing bits in Special Function Registers IP (Figure 23) and IPH (Figure 24). A lowerpriority interrupt can itself be interrupted by a higher-priority interrupt, but not by another interrupt of the same level. A high-priority level 3 interrupt cant be interrupted by any other interrupt source. If two request of different priority levels are received simultaneously, the request of higher priority level is serviced. If requests of the same priority level are received simultaneously, an internal polling sequence determines which request is serviced. Thus within each priority level there is a second priority structure determined by the polling sequence as follows:

Source Priority Within Level

45
1. IE0 (External Int 0) (highest) 2. TF0 (Timer 0) 3. IE1 (External Int 1) 4. TF1 (Timer 1) 5. RI+TI (UART) 6. TF2, EXF2 (Timer 2) (lowest) Note that the priority within level structure is only used to resolve simultaneous requests of the same priority level. The IP and IPH registers contain a number of unimplemented bits. User software should not write 1s to these positions, since they may be used in other 80C51 Family products.

How Interrupts Are Handled:


The interrupt flags are sampled at S5P2 of every machine cycle. The samples are polled during the following machine cycle. If one of the flags was in a set condition at S5P2 of the preceding cycle, the polling cycle will find it and the interrupt system will generate an LCALL to the appropriate service routine, provided this hardware-generated LCALL is not blocked by any of the following conditions: 1. An interrupt of equal or higher priority level is already in progress. 2. The current (polling) cycle is not the final cycle in the execution of the instruction in progress. 3. The instruction in progress is RETI or any write to the IE or IP registers. Any of these three conditions will block the generation of the LCALL to the interrupt service routine. Condition 2 ensures that the instruction in progress will be completed before vectoring to any service routine. Condition 3 ensures that if the instruction in progress is RETI or any access to IE or IP, then at least one more instruction will be executed before any interrupt is vectored to. The polling cycle is repeated with each machine cycle, and the values polled are the values that were present at S5P2 of the previous machine cycle. Note that if an interrupt flag is active but not being responded to for one of the above conditions, if the flag is not still active when the blocking condition is removed, the denied interrupt will not be serviced. In other words, the fact that the interrupt flag was once active but not serviced is not remembered. Every polling cycle is new.

46

47

External Interrupts:
The external sources can be programmed to be level-activated or transition-activated by setting or clearing bit IT1 or IT0 in Register TCON. If ITx = 0, external interrupt x is triggered by a detected low at the INTx pin. If ITx = 1, external interrupt x is edge triggered. In this mode if successive samples of the INTx pin show a high in one cycle and a low in the next cycle, interrupt request flag IEx in TCON is set. Flag bit IEx then requests the interrupt. Since the external interrupt pins are sampled once each machine cycle, an input high or low should hold for at least 12 oscillator periods to ensure sampling. If the external interrupt is transition-activated, the external source has to hold the request pin high for at least one cycle, and then hold it low for at least one cycle. This is done to ensure that the transition is seen so that interrupt request flag IEx will be set. IEx will be automatically cleared by the CPU when the service routine is called. If the external interrupt is level-activated, the external source has to hold the request active until the requested interrupt is actually generated. Then it has to deactivate the request before the interrupt service routine is completed, or else another interrupt will be generated.

Response Time
The INT0 and INT1 levels are inverted and latched into IE0 and IE1 at S5P2 of every machine cycle. The values are not actually polled by the circuitry until the next machine cycle. If a request is active and conditions are right for it to be acknowledged, a hardware subroutine call to the requested service routine will be the next instruction to be executed. The call itself takes two cycles. Thus, a minimum of three complete machine cycles elapse between activation of an external interrupt request and the beginning of execution of the first instruction of the service routine. Figure 25shows interrupt response timings. A longer response time would result if the

48
request is blocked by one of the 3 previously listed conditions. If an interrupt of equal or higher priority level is already in progress, the additional wait time obviously depends on the nature of the other interrupts service routine. If the instruction in progress is not in its final cycle, the additional wait time cannot be more the 3 cycles, since the longest instructions (MUL and DIV) are only 4 cycles long, and if the instruction in progress is RETI or an access to IE or IP, the additional wait time cannot be more than 5 cycles (a maximum of one more cycle to complete the instruction in progress, plus 4 cycles to complete the next instruction if the instruction is MUL or DIV). Thus, in a single-interrupt system, the response time is always more than 3 cycles and less than 9 cycles. As previously mentioned, the derivatives described in this data sheet have a four-level interrupt structure. The corresponding registers are IE, IP and IPH. (See Figures 22, 23, and 24.) The IPH (Interrupt Priority High) register makes the four-level interrupt structure possible. The function of the IPH SFR is simple and when combined with the IP SFR determines the priority of each interrupt. The priority of each interrupt is determined as shown in the following table:

An interrupt will be serviced as long as an interrupt of equal or higher priority is not already being serviced. If an interrupt of equal or higher level priority is being serviced, the new interrupt will wait until it is finished before being serviced. If a lower priority level interrupt is being serviced, it will be stopped and the new interrupt serviced. When the new interrupt is finished, the lower priority level interrupt that was stopped will be completed.

49

Reduced EMI
All port pins have slew rate controlled outputs. This is to limit noise generated by quickly switching output signals. The slew rate is factory set to approximately 10 ns rise and fall times.

Reduced EMI Mode


The AO bit (AUXR.0) in the AUXR register when set disables the ALE output.

Dual DPTR The dual DPTR structure (see Figure 26) enables a way to specify the address of an external data memory location. There are two 16-bit DPTR registers that address the external memory, and a single bit called DPS = AUXR1/bit0 that allows the program code to switch between them. New Register Name: AUXR1# SFR Address: A2H Reset Value: xxx000x0B

50

Where: DPS = AUXR1/bit0 = Switches between DPTR0 and DPTR1. Select Reg DPS DPTR0 0 DPTR1 1 The DPS bit status should be saved by software when switching between DPTR0 and DPTR1. Note that bit 2 is not writable and is always read as a zero. This allows the DPS bit to be quickly toggled simply by executing an INC DPTR instruction without affecting the WUPD bit.

DPTR Instructions

51
The instructions that refer to DPTR refer to the data pointer that is currently selected using the AUXR1/bit 0 register. The six instructions that use the DPTR are as follows: INC DPTR Increments the data pointer by 1 MOV DPTR, #data16 Loads the DPTR with a 16-bit constant MOV A, @ A+DPTR Move code byte relative to DPTR to ACC MOVX A, @ DPTR Move external RAM (16-bit address) to ACC MOVX @ DPTR , A Move ACC to external RAM (16-bit address) JMP @ A + DPTR Jump indirect relative to DPTR The data pointer can be accessed on a byte-by-byte basis by specifying the low or high byte in an instruction which accesses the SFRs. See application note AN458 for more details.

52

INTRODUCTION TO OPAMPS

53

OP-AMP
The op-amp is basically a differential amplifier having a large voltage gain, very high input impedance and low output impedance. The op-amp has a "inverting" or (-) input and "noninverting" or (+) input and a single output. The op-amp is usually powered by a dual polarity power supply in the range of +/- 5 volts to +/- 15 volts. A simple dual polarity power supply is shown in the figure below which can be assembled with two 9 volt batteries.

Inverting Amplifier:
The op-amp is connected using two resistors RA and RB such that the input signal is applied in series with RA and the output is connected back to the inverting input through RB. The noninverting input is connected to the ground reference or the center tap of the dual polarity power supply. In operation, as the input signal moves positive, the output will move negative and visa versa. The amount of voltage change at the output relative to the input depends on the ratio of the two resistors RA and RB. As the input moves in one direction, the output will move in the opposite direction, so that the voltage at the inverting input remains constant or zero volts in this case. If RA is 1K and RB is 10K and the input is +1 volt then there will be 1 mA of current flowing through RA and the output will have to move to -10 volts to supply the same current through RB and keep the voltage at the inverting input at zero. The voltage gain in this case would be RB/RA or 10K/1K = 10. Note that since the voltage at the inverting input is always zero, the input signal will see a input impedance equal to RA, or 1K in this case. For higher input impedances, both resistor values can be increased.

Noninverting Amplifier:
The noninverting amplifier is connected so that the input signal goes directly to the noninverting input (+) and the input resistor RA is grounded. In this configuration, the input impedance as seen by the signal is much greater since the input will be following the applied signal and not held

54
constant by the feedback current. As the signal moves in either direction, the output will follow in phase to maintain the inverting input at the same voltage as the input (+). The voltage gain is always more than 1 and can be worked out from Vgain = (1+ RB/RA).

Voltage Follower:
The voltage follower, also called a buffer, provides a high input impedance, a low output impedance, and unity gain. As the input voltage changes, the output and inverting input will change by an equal amount.

55

The figure shows the pin diagram of the LM358 chip. This chip is a low power dual opamp which was used for this experiment. The op-amp in this chip is called a voltage follower because the voltage that goes into the chip is the same as the voltage leaving the chip. This chip is used to separate the ladder circuit from the led and the ADC circuits.

FEATURES OF LM358 Available in 8-Bump micro SMD chip sized package, Internally frequency compensated for unity gain Large dc voltage gain: 100 dB Wide bandwidth (unity gain): 1 MHz (temperature compensated) Wide power supply range: Single supply: 3V to 32V or dual supplies: 1.5V to 16V Very low supply current drain (500 A)-essentially independent of supply voltage

56
Low input offset voltage: 2 Mv Input common-mode voltage range includes ground Differential input voltage range equal to the power supply voltage Large output voltage swing

PARAMETER TABLE Gain bandwidth Channels Input output type Slew Rate Supply Current Per Channel Supply Min Supply Max Offset Voltage max, 25C 1 MHz 2 Vcm to V-, Not R-R Out 0.1 Volts/usec 0.25 mA 3 Volt 32 Volt 3, 7 mV

LM 35 The LM35 series are precision integrated-circuit temperature sensors, whose output voltage is linearly proportional to the Celsius (Centigrade) temperature. The LM35 thus has an advantage over linear temperature sensors calibrated in Kelvin, as the user is not required to subtract a large constant voltage from its output to obtain convenient Centigrade scaling. The LM35 does not require any external calibration or trimming to provide typical accuracies of C at room temperature and C over a full -55 to +150C temperature range. Low cost is assured by trimming and calibration at the wafer level. The LM35's low output impedance, linear output, and precise inherent calibration make interfacing to readout or control circuitry especially easy. It can be used with single power supplies, or with plus and minus supplies. As it draws only 60 A from its supply, it has very low self-heating, less than 0.1C in still air. The LM35 is rated to operate over a -55 to +150C temperature range, while the LM35C is rated for a -40 to +110C range (-

57
10 with improved accuracy). The LM35 series is available packaged in hermetic TO-46 transistor packages, while the LM35C, LM35CA, and LM35D are also available in the plastic TO-92 transistor package. The LM35D is also available in an 8-lead surface mount small outline package and a plastic TO-220 package.

Features Calibrated directly in Celsius (Centigrade) Linear a 10.0 mV/C scale factor 0.5C accuracy guaranteeable (at a25C) Rated for full b55 to a150C range Suitable for remote applications Low cost due to wafer-level trimming Operates from 4 to 30 volts Less than 60 mA current drain Low self-heating, 0.08C in still air Nonlinearity only g(/4C typical Low impedance output, 0.1 X for 1 mA load

Pin diagram of lm 35

58

INTERFACING DEVICES

59

INTERFACING HEART BEAT MONITORING SYSTEM TO MICROCONTROLLER


5 V

R 6 0 2 2 0

R 5 9 1 0 K C 5 7 3 0 . 1 u f R 6 1 1 0 0 K 3 R 2 8 U 1 L 4 M 3 5 8 1 R P 2 6 O 5 T 2 3 2 9 A 5 6 5 V U + L M 3 5 8 1 7 3 0 P 2 . 0

+ -

MICROCO NTROLLE R

D L

1 E

5 D

R R

R 7 K

3R

6P 6 O

Microcontroller The heart beat monitoring system is connected to the port 2 pin of microcontroller
E communicatio R/W W INTERFACING LCD TO MICROCONTROLLER: ns bus R S AT89S52 DB7DB0

LCD control

60

Fig:15 Interfacing LCD to microcontroller A typical LCD write operation takes place as shown in the following timing waveform:

Fig:16 LCD Data waveform The interface is either a 4-bit or 8-bit parallel bus that allows fast reading/writing of data to and from the LCD.This waveform will write an ASCII Byte out to the LCD's screen . The ASCII code to be displayed is eight bits long and is sent to the LCD either four or eight bits at a time. If 4-bit mode is used, two nibbles of data (First high four bits and

61
then low four bits with an E Clock pulse with each nibble) are sent to complete a full eight-bit transfer. The E Clock is used to initiate the data transfer within the LCD.8-bit mode is best used when speed is required in an application and at least ten I/O pins are available. 4-bit mode requires a minimum of six bits. In 4-bit mode, only the top 4 data bits (DB4-7) are used. The R/S pin is used to select whether data or an instruction is being transferred between the microcontroller and the LCD. If the pin is high, then the byte at the current LCD Cursor Position can be read or written. If the pin is low, either an instruction is being sent to the LCD or the execution status of the last instruction is read back (whether or not it has completed).

Table: 9 LCD commands

INTERFACING TEMPERATURE MONITORING SYSTEM (LM35) TO ADC

V 8

U V

2 7 S V+ O U 1 T

2 2 2 1 2 3 4 5 5 V 1 1 P P P 2 . 5 2 . 6 2 . 7 1 9 7

5 / S

U 2 8 6 7 I N 0 8 I N 1 I N 2 I N 3 I N 4 I N 5 I N 6 I N 7 2 6 R R 0 C O E A E E F F + S

D D D D D D D D A A A

0 1 2 3 4 5 6 7

1 1 1 8 1 1 2 2

7 4 5 8 9 0 1 5 4 3 2T

P P P P P P P P P P P P P

1 1 1 1 1 1 1 1 2 2 2 2 2

. . . . . . . .

0 1 2 3 4 5 6 7

2 0 2 1 2 2

. 0 . 1 . 2 . 3 . 4

L K E O D C C 0

6 T A R2 A L E 9

8 0

62

Output pin of LM35 (Vout) is connected to the input port of ADC(0809)

ANALOG TO DIGITAL CONVERTER INTERFACE TO MICROCONTROLLER

The ADC0808, ADC0809 data acquisition component is a monolithic CMOS device with an 8bit analog-to-digital converter, 8-channel multiplexer and microprocessor compatible control logic. The 8-bit A/D converter uses successive approximation as the conversion technique. The converter features a high impedance chopper stabilized comparator, a 256R voltage divider with analog switch tree and a successive approximation register. The 8-channel multiplexer can directly access any of 8-single-ended analog signals. The device eliminates the need for external zero and full-scale adjustments. Easy interfacing to microprocessors is provided by the latched and decoded multiplexer address inputs and latched TTL TRI-STATE outputs. The design of the ADC0808, ADC0809 has been optimized by incorporating the most desirable aspects of several A/D conversion techniques. The ADC0808, ADC0809 offers high speed, high accuracy, minimal temperature dependence, excellent long-term accuracy and repeatability, and consumes minimal power. These features make this device ideally suited to applications from process and machine control to consumer and automotive applications. For 16-channel multiplexer with common output (sample/hold port)

63

(IN0 IN7): input pins Pin nos (17-21) : output pins Vref : reference voltage Start : start of conversion Eoc : end of conversion

64

The pins of ADC(10,9,2,17,14,15,8,18-25) are connected to the port 1 and port 2 of microcontroller

REGULATED POWER SUPPLY Power supply is an important part of operation of the Microcontroller. Microcontroller operates at +5v DC and also for other ICs and displays. A variable regulated power supply, also called a variable bench power supply, is one where you can continuously adjust the output voltage to your requirements. Varying the output of the power supply is the recommended way to test a project after having double checked parts placement against circuit drawings and the parts placement guide. This type of regulation is ideal for having a simple variable bench power supply. Actually this is quite important because one of the first projects a hobbyist should undertake is the construction of a variable regulated power supply. While a dedicated supply is quite handy e.g. 5V or 12V, it's much handier to have a variable supply on hand, especially for testing. Most digital logic circuits and processors need a 5 volt power supply. To use these parts we need to build a regulated 5 volt source.

65
Usually you start with an unregulated power To make a 5 volt power supply, we use a LM7805 voltage regulator IC (Integrated Circuit). The IC is shown below.

The LM7805 is simple to use. You simply connect the positive lead of your unregulated DC power supply (anything from 9VDC to 24VDC) to the Input pin, connect the negative lead to the Common pin and then when you turn on the power, you get a 5 volt supply from the Output pin.

CIRCUIT FEATURES

Brief description of operation: Gives out well regulated +5V output, output current capability of 100 mA Circuit protection: Built-in overheating protection shuts down output when regulator IC gets too hot Circuit complexity: Very simple and easy to build Circuit performance: Very stable +5V output voltage, reliable operation Availability of components: Easy to get, uses only very common basic components Design testing: Based on datasheet example circuit, I have used this circuit succesfully as part of many electronics projects Applications: Part of electronics devices, small laboratory power supply

66

Power supply voltage: Unreglated DC 8-18V power supply Power supply current: Needed output current + 5 mA Component costs: Few dollars for the electronics components + the input transformer cost

BLOCK DIAGRAM

67

EXAMPLE CIRCUIT DIAGRAM:

68

SMALL DEVICE C COMPILER

INTRODUCTION TO SDCC(COMPILATION TOOL)


SMALL DEVICE C COMPILER
SDCC is a retargettable, optimizing ANSI - C compiler that targets the Intel 8051, Maxim 80DS390, Zilog Z80 and the Motorola 68HC08 based MCUs. Work is in progress on supporting the Microchip PIC16 and PIC18 series. SDCC is Free Open Source Software, distributed under GNU General Public License (GPL).

FEATURES

ASXXXX and ASLINK, a Freeware, retargettable assembler and linker. extensive MCU specific language extensions, allowing effective use of the underlying hardware. A host of standard optimizations such as global sub expression elimination, loop optimizations (loop invariant, strength reduction of induction variables and loop

69
reversing ), constant folding and propagation, copy propagation, dead code elimination and jump tables for 'switch' statements.

MCU specific optimizations, including a global register allocator. Adaptable MCU specific backend that should be well suited for other 8 bit MCUs Independent rule based peep hole optimizer. A full range of data types: char (8 bits, 1 byte), short (16 bits, 2 bytes), int (16 bits, 2 bytes), long (32 bit, 4 bytes) and float (4 byte IEEE). The ability to add inline assembler code anywhere in a function. The ability to report on the complexity of a function to help decide what should be rewritten in assembler. A good selection of automated regression tests.

SDCC also comes with the source level debugger SDCDB, using the current version of Daniel's s51 simulator. SDCC was written by Sandeep Dutta and released under a GPL license. Since its initial release there have been numerous bug fixes and improvements. As of December 1999, the code was moved to SourceForge where all the "users turned developers" can access the same source tree. SDCC is constantly being updated with all the users' and developers' input. AVR and gbz80 ports are no longer maintained.

SDCC SUPPORTS FOLLOWING PLATFORMS


Linux - x86, Microsoft Windows - x86 and Mac OS x - ppc are the primary, so called "officially supported" platforms. SDCC compiles natively on Linux and Mac OS X using using gcc. Windows release and snapshot builds are made by cross compiling to mingw32 on a Linux host. Windows 9x/NT/2000/XP users are recommended to use Cygwin (http://sources.redhat.com/cygwin/) or may try the unsupported Borland C compiler or Microsoft Visual C++ build scripts.

70
SUPPORT OF SDCC SDCC and the included support packages come with fair amounts of documentation and examples. When they aren't enough, you can find help in the places listed below. Here is a short check list of tips to greatly improve your chances of obtaining a helpful response. 1. Attach the code you are compiling with SDCC. It should compile "out of the box". Snippets must compile and must include any required header files, etc. Incomplete information will hamper your chance of a timely response. 2. Specify the exact command you use to run SDCC, or attach your Makefile. 3. Specify the SDCC version (type "sdcc -v"), your platform and operating system. 4. Provide an exact copy of any error message or incorrect output.

SDCC SCREEN SHOT :

71

USING SDCC Getting Started: Download SDCC from http://sdcc.sourceforge.net/ If you are developing on a Windows platform I strongly recommend youget http://prdownloads.sourceforge.net/sdcc/sdcc-2.5.0-setup.exe (orwhatever is the latest revision) because it has an install wizard which will copy the files and will ask you if you want SDCC added to your path(HINT: I recommend you add SDCC to your path!)

The most up-to-date documentation is at http://sdcc.sourceforge.net/doc/sdccman.html/. SDCC also comes with anolder revision of

the same documentation which is installed in C:\Program Files\SDCC\doc\sdccman.html\index.html by default.

72
Students have reported experiencing problems with rev 2.3.0 and rev2.4.0 of SDCC, so make sure you are using rev 2.5.0 or newer.

SDCC Memory Models


SDCC basically has two memory models: Small and Large The large memory model will allocate all variables in external RAM by DEFAULT " Variables stored in internal RAM must be declared with the data or near keyword The small memory model will allocate all variables in internal, directlyaddressable RAM by default " Variables stored in external RAM must be declared with the xdata or far keyword ! SDCC recommends the use of the small memory model for more efficient code. However, for this class, since we are using combined program and data memory spaces, I think it is safer to use the large memory model. ! Be aware that, regardless of the memory model you choose, if you do not explicitly declare a pointer as data/near or xdata/far it will be 3 bytes!

SDCC Basics

Assuming that the location of SDCC is defined in your path, you can use the following syntax for your header files: #include <stdio.h> To use SDCC on the command line, use a command line syntax similar to the following (note: a more complete list of flags is shown in the example makefile later): sdcc --code-loc 0x6000 --xram-loc 0xB000 file.c

73

SDCC will generate the following output files: file.asm Assembler file created by the compiler file.lst Assembler listing file created by the assembler file.rst Assembler listing file updated by the linkage editor file.sym Symbol listing created by the assembler file.rel Object file created by the assembler, Input to the linkage editor file.map Memory map for the load module created by the linker file.mem Summary of the memory usage file.ihx This is the load module in Intel hex format By default SDCC uses the small memory model The assembler is given the memory locations as .area directives instead ofORG statements. You must remember to use the --code-loc and --xram-loc directives because this tells the linker where to place things in memory! You can examine the file.rst and file.map output files to verify that your code and data are assigned to the correct location. !

SDCC standard library routines


Most standard routines are present (printf, malloc, etc) However: " printf depends on putchar() which is not implemented. You must implement putchar() This allows you to decide where printf is displayed (on a terminal via serial port, on an LCD, etc) The putchar() function must have the following format: void putchar(char c);

74
If you need a getchar() function, the format is: char getchar(); malloc depends on having heap space created but SDCC does notautomatically create heap space for your program. You must provide heap space for malloc to allocate memory from. This can be done by: #include <malloc.h> #define HEAP_SIZE 4000 unsigned char xdata heap[HEAP_SIZE]; void main() { init_dynamic_memory((MEMHEADER xdata *)heap, HEAP_SIZE); }

SDC INTERRUPT SUPPORT


To write an ISR in C, create a function similar to the following format: Void isr _ foo() interrupt 1 { } " This format tells SDCC to generate an interrupt vector (at offset0x0B from the --code-loc address) that calls isr _foo in response to interrupt 1. " It also tells SDCC to generate a RETI instruction instead of a RET instruction to return from a call to isr _foo(). o The standard code generated for the interrupt is not very efficient. SDCC

takes a conservative view and will save registers on the stack before executing any of your code in the ISR and it will restore those registers

75
before executing the RETI instruction. " You can use the keyword _naked to make your interrupt faster. This keyword will prevent SDCC from generating any entry/exit code to save registers for your ISR.

76

SNAPSHOTS

FLASH MAGIC

77
Flash Magic is a PC tool for programming flash based microcontrollers from NXP using a serial protocol while in the target hardware. Flash Magic is a feature-rich Windows based tool for the downloading of code into NXP flash microcontrollers. It utilises a feature of the microcontrollers called ISP, which allows the transfer of data serially between a PC and the device. Flash Magic can erase devices, program them, read data and read and set various configuration information. Rather than providing the basic features of ISP, Flash Magic adds additional features and intelligence, allowing complex operations to be performed. For example, erasing can be any collection of pages pages, blocks, the hex file to be programmed or the entire device. Some devices store the ISP bootloader in flash memory, so Flash magic implements methods to protect this code from being erased. Additional advanced features of Flash Magic include the automatic programming of checksums, entering ISP mode via a serial command, execution of Just In Time modules allowing endless flexibility in the data programmed, control over RS232 signals to place devices into ISP mode, and control over the timing of such signals. Flash Magic has been available for free for over six years and supports all current 8-bit (8051), 16-bit (XA) and 32-bit (ARM) flash microcontrollers from NXP. . Possible Uses Some ideas for applications built on the Flash Magic platform:

Custom ISP tool for in-house use, for example production line programming where it is essential the user interface is simplified as much as possible End user ISP tool for updating the firmware of products. You can build the hex file into the application or allow it to be fetched over the internet. Adverts for new products could be displayed to the user. Use one tool for all your products involving potentially multiple NXP microcontrollers.

Gang programming tool. Invoke multiple instances of the Flash Magic DLL in seperate threads, each using a different COM port to allow parallel ISP programming Future-proofing products. Rather than write your own ISP tool and have to keep updating it for new NXP devices, updates to the DLL will automatically add new devices

78

Flash magic Screenshots

79

Step 1 Connection Settings

Step 2 Erasing

Step 3 Selecting the Hex File

80

Displaying Memory

Features

Straightforward and intuitive user interface Five simple steps to erasing and programming a device and setting any options desired Programs Intel Hex Files

81

Automatic verifying after programming Fills unused Flash to increase firmware security Ability to automatically program checksums. Using the supplied checksum calculation routine your firmware can easily verify the integrity of a Flash block, ensuring no unauthorized or corrupted code can ever be executed

Program security bits Check which Flash blocks are blank or in use with the ability to easily erase all blocks in use Read the device signature

Display the contents of Flash in ASCII and Hexadecimal formats Single-click access to the manual, Flash Magic home page and NXP Microcontrollers home page Ability to use high-speed serial communications on devices that support it. Flash Magic calculates the highest baudrate that both the device and your PC can use and switches to that baudrate transparently

Command Line interface allowing Flash Magic to be used in IDEs and Batch Files Manual in PDF format Supports half-duplex communications Verify Hex Files previously programmed Able to reset Rx2 and 66x devices (revision G or higher) Able to control the DTR and RTS RS232 signals when connected to RST and /PSEN to place the device into BootROM and Execute modes automatically. An example circuit diagram is included in the Manual. Essential for ISP with target hardware that is hard to access.

Able to play any Wave file when finished programming. Built in automated version checker - helps ensure you always have the latest version. Powerful, flexible Just In Time Code feature. Write your own JIT Modules to generate last minute code for programming. Uses include:
o o o

Serial number generation Copy protection and copy authorization Storing program date and time - manufacture date

82
o o o o o

Storing program operator and location Lookup table generation Language tables or language selection Centralized record keeping Obtaining latest firmware from the Corporate Web site or project intranet

Features automatically updating Internet links including links to related technical documents, software updates, utilities and code examples, using EmbeddedHints technology

Displays information about the selected Hex File, including the creation and modification dates, flash memory used, percentage of the current device used Completely free! Flash Magic works on any versions of Windows, except Windows 95. 10Mb of disk space is required

83

INTERFACING PROGRAMS

84

/***********************************************************************

Module Version

: AdcV1 -- Adc Interfacing Module Version1 . : 1.0

Description:

This module is to interface ADC to the microcontroller. It is interfaced on P1(DATA), P2(Commands).

****************************************************************************** ************/ # include <8052.h> # ifndef __ADC_V1__ # define __ADC_V1__ # define D0 # define D1 # define D2 # define D3 # define D4 # define D5 # define D6 # define D7 # define D # define ADDR_A # define ADDR_B # define ADDR_C P3_5 P3_6 P1_0 P1_1 P1_2 P1_3 P1_4 P1_5 P1_6 P1_7 P1 P3_4

85
# define LIGHT_SENS 1 # define TEMP_SENS 0 # define FIRE_SENS 2 # define SC # define EOC # define OE # define ALE P2_0 P2_1 P2_2 P3_7 = 0, = 0, = 0;

unsigned char gucSensor0Val gucSensor1Val gucSensor2Val

void ReadSensorData(unsigned char ucAddr, unsigned char *ucpValue); void AdcDelay1ms(void); void ReadSensorData(unsigned char ucAddr,unsigned char *ucpValue) { unsigned int ucDelay = 0; unsigned int ucValue = 0; switch(ucAddr) { case 0: //TEMP_SENS: ADDR_A = 1; ADDR_B = 1; ADDR_C = 0; break; case 1: //LIGHT_SENS: ADDR_A = 0; ADDR_B = 0; ADDR_C = 1; break; case 2:

86
ADDR_A = 0; ADDR_B = 0; ADDR_C = 0; break; default: break; } AdcDelay1ms(); ALE=1; SC = 1; AdcDelay1ms(); ALE = 0; SC = 0; while(EOC == 1); while(EOC == 0); for(ucDelay = 0; ucDelay < 10; ucDelay++) AdcDelay1ms(); OE = 1; AdcDelay1ms(); *ucpValue = D; OE = 0; } void AdcDelay1ms(void) { unsigned int x,y; for(x = 0; x < 1200; x++) for(y = 0; y < 3; y++); }

87

# endif

/****************************************************************************

Project : Version : Author :

HeartBeat & Temperature Monitor 1.0 1.

*****************************************************************************/ # include <p89v51rd2.h> # include "LcdV1.h" // On P0 # include "AdcV1.h" // On P1 & P2 # include "VerV1.h" // No Port unsigned int guiIterations = 0; unsigned char IsAlnum(unsigned char ucCh); unsigned char gucPulseValues1 = 0; unsigned char gucPulseValues2 = 0; void main(void) { unsigned int i j unsigned char ucAddrCounter ucSensorValue[3], ucAscii[4]; DisplayVersion(); for(i = 0; i < 10; i++) for(j = 0; j < 40000; j++); LcdInit(); = 0, = 0; = 0,

88

while(1) { for(ucAddrCounter = 0; ucAddrCounter < 2; ucAddrCounter++) { ReadSensorData(ucAddrCounter, &ucSensorValue[ucAddrCounter]); //ucSensorValue[ucAddrCounter] = 15; ToAsciiDecimal(ucSensorValue[ucAddrCounter],&ucAscii[0]);

LcdInit(); switch(ucAddrCounter) { case 0: //TEMP_SENS: LcdPuts("Temp Value : "); LcdCmd(NEW_LINE); LcdPuts(" ");

LcdPutc(ucAscii[0]); if(ucSensorValue[ucAddrCounter] > 10) LcdPutc(ucAscii[1]); if(ucSensorValue[ucAddrCounter] > 100) LcdPutc(ucAscii[2]); break; case 1://LIGHT_SENS: LcdPuts("Pulse Value : "); LcdCmd(NEW_LINE); LcdPuts(" ");

/*LcdPutc(ucAscii[0]); if(ucSensorValue[ucAddrCounter] > 10) LcdPutc(ucAscii[1]);

89
if(ucSensorValue[ucAddrCounter] > 100) LcdPutc(ucAscii[2]); */ if(ucSensorValue[ucAddrCounter] >= 15) { /* Display Hear Pulse */ ToAsciiDecimal(ucSensorValue[ucAddrCounter],&ucAscii[0]); LcdPutc(ucAscii[0]); if(ucSensorValue[ucAddrCounter] > 10) LcdPutc(ucAscii[1]); if(ucSensorValue[ucAddrCounter] > 100) LcdPutc(ucAscii[2]);

} else { /* Display Hear Pulse */ ucSensorValue[ucAddrCounter] = 0; //gucValues2[gucPulseValues2]; ToAsciiDecimal(ucSensorValue[ucAddrCounter],&ucAscii[0]); LcdPutc(ucAscii[0]); }

break; default: break; } /* End of Switch */

90

//for(i = 0; i < 2; i++) for(j = 0; j < 40000; j++); }/* End of for(sensor) */ guiIterations++; } /* End of While(1) */ } /* End of Main() */ / ****************************************************************************** **/ unsigned char IsAlnum(unsigned char ucCh) { if( ((ucCh >= 'A') && (ucCh <= 'Z')) || ((ucCh >= 'a') && (ucCh <= 'z')) || ((ucCh >= '0') && (ucCh <= '9'))) return 1; else return 0; } / ****************************************************************************** **/

91

/ ****************************************************************************** **********

Module Version

: LcdV2 - Lcd Interfacing module Version 1. : 1.0 This module is to interface Lcd to the microcontroller. It is interfaced on P0 in 4-bit mode.

Description:

****************************************************************************** ************/ # include <8052.h> # ifndef __LCD_V1__ # define __LCD_V1__ /* ******************************************************************** Macro Definitions */ # define LCD_DELAY 400 # define LCD_PORT P0 # define RS # define RW # define EN P0_0 P0_1 P0_2

# define INIT_CMD 0x0F # define NEW_LINE 0xC0 /* ********************************************************************* Global Variables */

92
bit gbStatus = 0; /* ****************************************************************************** ********* */ void Delay(unsigned int j) { unsigned int i; for(i = 0; i < j ; i++); } /* ****************************************************************************** ********* */ void LcdInitWrite(unsigned char ucCmd) { RS = 0; RW = 0; LCD_PORT = ucCmd; } /* ****************************************************************************** ********* */ void LcdCmd(unsigned char ucCmd) { unsigned char ucTemp; if(gbStatus) { gbStatus=0; goto NEXT; } RS = 0;

93
NEXT: RW = 0; ucTemp = ucCmd; ucTemp &= 0xf0; LCD_PORT |= ucTemp; EN = 1; ucTemp = (ucCmd << 4); ucTemp &= 0xf0; LCD_PORT |= ucTemp; EN = 1; } /* ****************************************************************************** ********* */ void LcdData(unsigned char ucData) { gbStatus = 1; RS = 1; LcdCmd(ucData); } /* ****************************************************************************** ********* */ void LcdInit(void) { Delay(LCD_DELAY); LcdInitWrite(0x30); Delay(LCD_DELAY); LcdInitWrite(0x30); Delay(LCD_DELAY); LcdInitWrite(0x30); Delay(LCD_DELAY);

94
LcdInitWrite(0x20); Delay(LCD_DELAY); LcdCmd(0x28); Delay(LCD_DELAY); LcdCmd(4); Delay(LCD_DELAY); LcdCmd(0x85); Delay(LCD_DELAY); LcdCmd(6); Delay(LCD_DELAY); LcdCmd(1); Delay(LCD_DELAY); } /* ****************************************************************************** ********* */ void LcdPuts(unsigned char *ucStr) { unsigned int i; for(i = 0; ucStr[i] !=0 ; i++) LcdData(ucStr[i]); } /* ****************************************************************************** ********* */ void LcdPutc(unsigned char ucCh) { LcdData(ucCh); }

95
/* ****************************************************************************** ********* */ void LcdGotoXy(unsigned char x, unsigned char y) { if(x == 0) { LcdCmd(0x80 + y); } if(x == 1) { LcdCmd(0xc0 + y); } } /* ************************************************************************* */ void LcdClear(void) { LcdCmd(0x01); } /* ****************************************************************************/ # endif

96

CONCLUSION

In this project we have dealt with project which time and errors that may occur in manual systems .This project is implemented in embedded systems so it has a large scope of increasing popularity due to the ability of embedded systems to conquer modern society . We also knew that this heart beat and temperature monitaring system is much useful in the gym centers which is much concentrating on heart rate which can measure the cardiovascular and physcological stress and temperature.. As the harder you exercise , higher the heart rate and temperature rises. To reduce the chance of injury and over training of heart during measurement., heart pulses and temperature are measured using corresponding sensors.. In this way we are comple6ting eliminating wastage of time ,at the same instant a matter of interest in the patients view. We can enlarge this application to all the medical and surgical purposes.

97

BIBLIOGRAPHY
1) The 8051 Micro controller and Embedded Systems Muhammad Ali Mazidi Janice Gillispie Mazidi 2) The 8051 Micro controller Architecture Programming & Applications Kenneth J.Ayala 3) Fundamentals of Micro processors and Micro computers B.Ram 4) Micro processor Architecture, Programming & Applications Ramesh S.Gaonkar 5) Electronic Components D.V.Prasad References on the Web: www.national.com www.atmel.com www.microsoftsearch.com www.geocities.com

98