Vous êtes sur la page 1sur 94

INDEX 1. Abbreviations 2. Figures locations 3. Abstract 4. Introduction 5. Block Diagram 5.1Block Diagram Description 6. Schematic 6.1Schematic Description 7.

Hardware Components Power supply Microcontroller LCD Keypad Buzzer H bridge DC MOTOR Metal detector ZIGBEE

8. Software components a. About Kiel b. Embedded C 9. Conclusion (or) Synopsis 10. Future Aspects 11. Bibliography Abbreviations Symbol ACC B PSW SP DPTR DPL Name Accumulator B register Program status word Stack pointer Data pointer 2 bytes Low byte

DPH P0 P1 P2 P3 IP IE TMOD TCON T2CON T2MOD TH0 TL0 TH1 TL1 TH2 TL2 SCON SBUF RFID MAX TTL ATM RS 232 AC DC LCD PC RPS RMS EEPROM ROM RAM BIOS SRAM EPROM DRAM ISR I2C TWI

High byte Port0 Port1 Port2 Port3 Interrupt priority control Interrupt enable control Timer/counter mode control Timer/counter control Timer/counter 2 control Timer/counter mode2 control Timer/counter 0high byte Timer/counter 0 low byte Timer/counter 1 high byte Timer/counter 1 low byte Timer/counter 2 high byte Timer/counter 2 low byte Serial control Serial data buffer Radio Frequency IDentification MAXIM (IC manufacturer ) Transistor to Transistor Logic Automatic Teller Machine Recommended Standard Alternating Current Direct Current Liquid Crystal Display Personal Computer Regulated Power Supply Root Mean Square Electrically Erasable Programmable ROM Read Only Memory Random Access Memory Basic Input Output System Static RAM Erasable Programmable ROM Dynamic Random Access Memory Interrupt Service Routine Inter Intergrated Chip Two Wire Interface

Figure Locations S.No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 Figure Components of Typical Linear Power Supply An Electrical Transformer Bridge Rectifier Bridge Rectifier Positive Cycle Bridge Rectifier Negative Cycle Three terminal voltage Regulator Functional Diagram of Microcontroller Pin Diagram of Microcontroller Oscillator connections External clock drive connections A register B register RAM RAM Allocation Register Banks PSW DPTR SP PORT 0 TL0 and TH0 DB9 Page No.

4. INTRODUCTION The aim of the project is design an unmanned robotic war head vehicle which can be used in the war fields which is remotely controlled via zig bee technology. This projects employees a tactual wheeled vehicle which is driven by two gear motor making it move in all required directions. The vehicle is mounted with a firing gun which can be rotated towards the target using a motor.

The vechile is provided with a bomb detector which can detect land mine with war crafts safety guiding the robotic system .a voiding to walk through such hazardous conditions. The whole system which is explained above gets the commands from the base station through zig bee wireless technology 5. Block Diagram TRNAMITTER SECTION: Power supply Zig bee transmitter

MICRO CONTROLLE R

Buzzer

Keypad LCD

RECEIVER SECTION:

zigbee

Micro controller

H Bridge

M1 M2

Bomb detector

H Bridge

M3

M4

5.1Block Diagram Description

Power Supply Section: This section is meant for supplying Power to all the sections mentioned above. It basically consists of a Transformer to step down the 230V ac to 9V ac followed by diodes. Here diodes are used to rectify the ac to dc. After rectification the obtained rippled dc is filtered using a capacitor Filter. A positive voltage regulator is used to regulate the obtained dc voltage. Microcontroller Section: This section forms the control unit of the whole project. This section basically consists of a Microcontroller with its associated circuitry like Crystal with capacitors, Reset circuitry, Pull up resistors (if needed) and so on. The Microcontroller forms the heart of the project because it controls the devices being interfaced and communicates with the devices according to the program being written.

Keypad Section: This section consists of a Linear Keypad. This keypad is used to enter the no. of liters of petrol required. The keypad is interfaced to microcontroller which continuously scans the keypad. LCD Display Section: This section is basically meant to show up the status of the project. This project makes use of Liquid Crystal Display to display / prompt for necessary information. Buzzer: buzzer is used for the indication purpose .so here the buzzer is used for detection of bomb in the middle of the path. H Bridge: h bridge is used for the driving of the two motors at a time. So that we can move the robot in the required direction. Dc Motor: dc motor is mainly used for the motion of the robot so here we use four motor .two motors for the motion of the robot, one motor for the rotation of the gun toward the target and fourth motor is used functioning of the gun. Metal Detector: metal detector is used for the detection of the bomb in the path of the vechile in the war field. Zig bee: zig bee is a wireless technology used for the distance of 20 to 80 meters. Here we can transfer the data from transmitter part to the receiver part beyond the distance using the different topology types.

6. SCHEMATIC Schematic Description 7.HARDWARE Components The Hardware components used in this project are Regulated Power Supply Microcontroller Keypad LCD Buzzer H Bridge Dc Motor Metal Detector ZIG BEE

7.1 REGULATED POWER SUPPLY The power supplies are designed to convert high voltage AC mains electricity to a suitable low voltage supply for electronic circuits and other devices. A RPS (Regulated Power Supply) is the Power Supply with Rectification, Filtering and Regulation being done on the AC mains to get a Regulated power supply for Microcontroller and for the other devices being interfaced to it. A power supply can by broken down into a series of blocks, each of which performs a particular function. A d.c power supply which maintains the output voltage constant irrespective of a.c mains fluctuations or load variations is known as Regulated D.C Power Supply For example a 5V regulated power supply system as shown below:

Transformer: A transformer is an electrical device which is used to convert electrical power from one Electrical circuit to another without change in frequency. Transformers convert AC electricity from one voltage to another with little loss of power. Transformers work only with AC and this is one of the reasons why mains electricity is AC. Step-up transformers increase in output voltage, step-down transformers decrease in output voltage. Most power supplies use a step-down transformer to reduce the dangerously high mains voltage to a safer low voltage. The input coil is called the primary and the output coil is called the secondary. There is no electrical connection between the two coils; instead they are linked by an alternating magnetic field created in the soft-iron core of the transformer. The two lines in the middle of the circuit symbol represent the core. Transformers waste very little power so the power out is (almost) equal to the power in. Note that as voltage is stepped down current is stepped up. The ratio of the number of turns on each coil, called the turns ratio, determines the ratio of the voltages. A step-down transformer has a large number of turns on its primary (input) coil which is connected to the high voltage mains supply, and a small number of turns on its secondary (output) coil to give a low output voltage.

An Electrical Transformer Turns ratio = Vp/ VS = Np/NS Power Out= Power In VS X IS=VP X IP Vp = primary (input) voltage Np = number of turns on primary coil Ip = primary (input) current

RECTIFIER: A circuit which is used to convert a.c to dc is known as RECTIFIER. The process of conversion a.c to d.c is called rectification TYPES OF RECTIFIERS: Half wave Rectifier Full wave rectifier 1. Centre tap full wave rectifier. 2. Bridge type full bridge rectifier. Comparison of rectifier circuits: Type of Rectifier Parameter Number of diodes 1 PIV of diodes Vm D.C output voltage Vdc,at no-load Ripple factor Ripple Vm/ 0.318Vm 1.21 2Vm 2Vm/ 0.636Vm 0.482 Vm 2Vm/ 0.636Vm 0.482 2 4 Half wave Full wave Bridge

frequency Rectification efficiency Transformer Utilization Factor(TUF) RMS voltage Vrms

f 0.406 0.287 Vm/2

2f 0.812 0.693 Vm/2

2f 0.812 0.812 Vm/2

Full-wave Rectifier: From the above comparison we came to know that full wave bridge rectifier as more advantages than the other two rectifiers. So, in our project we are using full wave bridge rectifier circuit. Bridge Rectifier: A bridge rectifier makes use of four diodes in a bridge arrangement to achieve full-wave rectification. This is a widely used configuration, both with individual diodes wired as shown and with single component bridges where the diode bridge is wired internally. A bridge rectifier makes use of four diodes in a bridge arrangement as shown in fig (a) to achieve full-wave rectification. This is a widely used configuration, both with individual diodes wired as shown and with single component bridges where the diode bridge is wired internally.

Fig (A)

Operation: During positive half cycle of secondary, the diodes D2 and D3 are in forward biased while D1 and D4 are in reverse biased as shown in the fig(b). The current flow direction is shown in the fig (b) with dotted arrows.

Fig (B) During negative half cycle of secondary voltage, the diodes D1 and D4 are in forward biased while D2 and D3 are in reverse biased as shown in the fig(c). The current flow direction is shown in the fig (c) with dotted arrows.

Fig(C) Filter: A Filter is a device which removes the a.c component of rectifier output but allows the d.c component to reach the load

Capacitor Filter: We have seen that the ripple content in the rectified output of half wave rectifier is 121% or that of fullwave or bridge rectifier or bridge rectifier is 48% such high percentages of ripples is not acceptable for most of the applications. Ripples can be removed by one of the following methods of filtering. (a) A capacitor, in parallel to the load, provides an easier by pass for the ripples voltage though it due to low impedance. At ripple frequency and leave the D.C. to appear at the load. (b) An inductor, in series with the load, prevents the passage of the ripple current (due to high impedance at ripple frequency) while allowing the d.c (due to low resistance to d.c)

(c) Various combinations of capacitor and inductor, such as L-section filter

section filter, multiple

section filter etc. which make use of both the properties mentioned in (a) and (b) above. Two cases of capacitor filter, one applied on half wave rectifier and another with full wave rectifier. Filtering is performed by a large value electrolytic capacitor connected across the DC supply to act as a reservoir, supplying current to the output when the varying DC voltage from the rectifier is falling. The capacitor charges quickly near the peak of the varying DC, and then discharges as it supplies current to the output. Filtering significantly increases the average DC voltage to almost the peak value (1.4 RMS value). To calculate the value of capacitor(C), C = *3*f*r*Rl Where, f = supply frequency, r = ripple factor, Rl = load resistance Note: In our circuit we are using 1000F hence large value of capacitor is placed to reduce ripples and to improve the DC component.

Regulator: Voltage regulator ICs is available with fixed (typically 5, 12 and 15V) or variable output voltages. The maximum current they can pass also rates them. Negative voltage regulators are available, mainly for use in dual supplies. Most regulators include some automatic protection from excessive current ('overload protection') and overheating ('thermal protection'). Many of the fixed voltage regulators ICs have 3 leads and look like power transistors, such as the 7805 +5V 1A regulator shown on the right. 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.

Fig 6.1.6 A Three Terminal Voltage Regulator 78XX: The Bay Linear LM78XX is integrated linear positive regulator with three terminals. The LM78XX offer several fixed output voltages making them useful in wide range of applications. When used as a zener diode/resistor combination replacement, the LM78XX usually results in an effective output impedance

improvement of two orders of magnitude, lower quiescent current. The LM78XX is available in the TO-252, TO-220 & TO-263packages, Features: Output Current of 1.5A Output Voltage Tolerance of 5% Internal thermal overload protection Internal Short-Circuit Limited Output Voltage 5.0V, 6V, 8V, 9V, 10V, 12V, 15V, 18V, 24V. 7.2 MICRO CONTROLLER 89S52 Introduction A Micro controller consists of a powerful CPU tightly coupled with memory, various I/O interfaces such as serial port, parallel port timer or counter, interrupt controller, data acquisition interfaces-Analog to Digital converter, Digital to Analog converter, integrated on to a single silicon chip. If a system is developed with a microprocessor, the designer has to go for external memory such as RAM, ROM, EPROM and peripherals. But controller is provided all these facilities on a single chip. Development of a Micro controller reduces PCB size and cost of design. One of the major differences between a Microprocessor and a Micro controller is that a controller often deals with bits not bytes as in the real world application. Intel has introduced a family of Micro controllers called the MCS-51. The Major Features: Compatible with MCS-51 products 4k Bytes of in-system Reprogrammable flash memory Fully static operation: 0HZ to 24MHZ Three level programmable clock 128 * 8 bit timer/counters Six interrupt sources Programmable serial channel Low power idle power-down modes

Why AT 89S52 The system requirements and control specifications clearly rule out the use of 16, 32 or 64 bit micro controllers or microprocessors. Systems using these may be earlier to implement due to large number of internal features. They are also faster and more reliable but, 8-bit micro controller satisfactorily serves the

above application. Using an inexpensive 8-bit Microcontroller will doom the 32-bit product failure in any competitive market place. Coming to the question of why to use AT89S52 of all the 8-bit microcontroller available in the market the main answer would be because it has 4 Kb on chip flash memory which is just sufficient for our application. The on-chip Flash ROM allows the program memory to be reprogrammed in system or by conventional non-volatile memory Programmer. Moreover ATMEL is the leader in flash technology in todays market place and hence using AT 89S52 is the optimal solution. AT89S52 MICROCONTROLLER ARCHITECTURE The 89S52 architecture consists of these specific features: Eight bit CPU with registers A (the accumulator) and B Sixteen-bit program counter (PC) and data pointer (DPTR) Eight- bit stack pointer (PSW) Eight-bit stack pointer (Sp) Internal ROM or EPROM (8751) of 0(8031) to 64K (89S52) Internal RAM of 128 bytes: 1. Four register banks, each containing eight registers 2. Sixteen bytes, which may be addressed at the bit level 3. Eighty bytes of general- purpose data memory Thirty two input/output pins arranged as four 8-bit ports:p0-p3 Two 16-bit timer/counters: T0 and T1 Full duplex serial data receiver/transmitter: SBUF Control registers: TCON, TMOD, SCON, PCON, IP, and IE Two external and three internal interrupts sources. Oscillator and clock circuits.

Functional block diagram of micro controller The 89S52 oscillator and clock: The heart of the 89S52 circuitry that generates the clock pulses by which all the internal all internal operations are synchronized. Pins XTAL1 And XTAL2 is provided for connecting a resonant network to form an oscillator. Typically a quartz crystal and capacitors are employed. The crystal frequency is the basic internal clock frequency of the microcontroller. The manufacturers make 89S52 designs that run at specific minimum and maximum frequencies typically 1 to 16 MHz.

Fig 3.7.2: - Oscillator and timing circuit Types of memory: The 89C51 have three general types of memory. They are on-chip memory, external Code memory and external Ram. On-Chip memory refers to physically existing memory on the micro controller itself. External code memory is the code memory that resides off chip. This is often in the form of an external EPROM. External RAM is the Ram that resides off chip. This often is in the form of standard static RAM or flash RAM. a) Code memory Code memory is the memory that holds the actual 89S52 programs that is to be run. This memory is limited to 64K. Code memory may be found on-chip or off-chip. It is possible to have 4K of code memory on-chip and 60K off chip memory simultaneously. If only off-chip memory is available then there can be 64K of off chip ROM. This is controlled by pin provided as EA b) Internal RAM

The 89S52 have a bank of 128 of internal RAM. The internal RAM is found on-chip. So it is the fastest Ram available. And also it is most flexible in terms of reading and writing. Internal Ram is volatile, so when 89C51 is reset, this memory is cleared. 128 bytes of internal memory are subdivided. The first 32 bytes are divided into 4 register banks. Each bank contains 8 registers. Internal RAM also contains 128 bits, which are addressed from 20h to 2Fh. These bits are bit addressed i.e. each individual bit of a byte can be addressed by the user. They are numbered 00h to 7Fh. The user may make use of these variables with commands such as SETB and CLR. FLASH MEMORY: Flash memory (sometimes called "flash RAM") is a type of constantly-powered non volatile that can be erased and reprogrammed in units of memory called blocks. It is a variation of electrically erasable programmable read-only memory (EEPROM) which, unlike flash memory, is erased and rewritten at the byte level, which is slower than flash memory updating. Flash memory is often used to hold control code such as the basic input/output system (BIOS) in a personal computer. When BIOS needs to be changed (rewritten), the flash memory can be written to in block (rather than byte) sizes, making it easy to update. On the other hand, flash memory is not useful as random access memory (RAM) because RAM needs to be addressable at the byte (not the block) level. Flash memory gets its name because the microchip is organized so that a section of memory cells are erased in a single action or "flash." The erasure is caused by Fowler-Nordheim tunneling in which electrons pierce through a thin dielectric material to remove an electronic charge from a floating gate associated with each memory cell. Intel offers a form of flash memory that holds two bits (rather than one) in each memory cell, thus doubling the capacity of memory without a corresponding increase in price. Flash memory is used in digital cellular phones, digital cameras, LAN switches, PC Cards for notebook computers, digital set-up boxes, embedded controllers, and other devices.

Features Memory Type FLASH ROM Read-Only Memory SRAM Static Random-Access Memory Low-cost, high-density, high-speed architecture; low power; high reliability Mature, high-density, reliable, low cost; time-consuming mask required, suitable for high production with stable code Highest speed, high-power, low-density memory; limited density drives up cost

EPROM Memory EEPROMorE2PROM Electrically Erasable Read-Only Memory DRAM Dynamic Random Access Memory

High-density memory; must be exposed

Electrically Programmable Read-Only to ultraviolet light for erasure Electrically byte-erasable; lower

Programmable reliability, higher cost, lowest density

High-density, high-power

low-cost,

high-speed,

Technical Overview of Flash Memory Flash memory is a nonvolatile memory using NOR technology, which allows the user to electrically program and erase information. Intel Flash memory uses memory cells similar to an EPROM, but with a much thinner, precisely grown oxide between the floating gate and the source (see Figure 2). Flash programming occurs when electrons are placed on the floating gate. The charge is stored on the floating gate, with the oxide layer allowing the cell to be electrically erased through the source. Intel Flash memory is an extremely reliable nonvolatile memory architecture.

Fig 3.7.3: - Pin diagram of AT89S52 Pin Description: VCC: Supply voltage. GND: Ground. Port 0: Port 0 is an 8-bit open-drain bi-directional I/O port. As an output port, each pin can sink eight TTL inputs. When ones are written to port 0 pins, the pins can be used as high impedance inputs. Port 0 may also be configured to be the multiplexed low order address/data bus during accesses to external program and data memory. In this mode P0 has internal pull-ups. Port 0 also receives the code bytes during Flash programming, and outputs the code bytes during program verification. External pull-ups are required during program verification. Port 1: Port 1 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 1 output buffers can sink/source four TTL inputs. When 1s are written to Port 1 pins they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. Port 1 also receives the low-order address bytes during Flash programming and verification. Port 2: Port 2 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 2 output buffers can sink/source four TTL inputs. When 1s are written to Port 2 pins they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 2 pins that are externally being pulled low will source current (IIL) because of the internal pull-ups. Port 2 emits the high-order address byte during fetches from external program memory and during accesses to external data memories that use 16-bit addresses (MOVX @DPTR). In this application, it uses strong internal pull-ups when emitting 1s. During accesses to external data memories that use 8-bit addresses (MOVX @ RI), Port 2 emits the contents of the P2 Special Function Register. Port 2 also receives the high-order address bits and some control signals during Flash programming and verification. Port 3: Port 3 is an 8-bit bi-directional I/O port with internal pull-ups. The Port 3 output buffers can sink/source four TTL inputs. When 1s are written to Port 3 pins they are pulled high by the internal pull-ups and can be used as inputs. As inputs, Port 3 pins that are externally being pulled low will source current (IIL) because of the pull-ups.

Port 3 also serves the functions of various special features of the AT89C51 as listed below: Port 3 also receives some control signals for Flash programming and verification

Tab 6.2.1 Port pins and their alternate functions RST: Reset input. A high on this pin for two machine cycles while the oscillator is running resets the device. ALE/PROG: Address Latch Enable output pulse for latching the low byte of the address during accesses to external memory. This pin is also the program pulse input (PROG) during Flash programming. In normal operation ALE is emitted at a constant rate of 1/6the oscillator frequency, and may be used for external timing or clocking purposes. Note, however, that one ALE pulse is skipped during each access to external Data Memory. If desired, ALE operation can be disabled by setting bit 0 of SFR location 8EH. With the bit set, ALE is active only during a MOVX or MOVC instruction. Otherwise, the pin is pulled high. Setting the ALEdisable bit has no effect if the microcontroller is in external execution mode. PSEN: Program Store Enable is the read strobe to external program memory. When the AT89C51 is executing code from external program memory, PSEN is activated twice each machine cycle, except that two PSEN activations are skipped during each access to external data memory. EA/VPP: External Access Enable EA must be strapped to GND in order to enable the device to fetch code from external program memory locations starting at 0000H up to FFFFH.

Note, however, that if lock bit 1 is programmed, EA will be internally latched on reset. EA should be strapped to VCC for internal program executions. This pin also receives the 12-volt programming enable voltage (VPP) during Flash programming, for parts that require 12-volt VPP. XTAL1: Input to the inverting oscillator amplifier and input to the internal clock operating circuit.

XTAL2: It is the Output from the inverting oscillator amplifier. Oscillator Characteristics: XTAL1 and XTAL2 are the input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in Figs 6.2.3. Either a quartz crystal or ceramic resonator may be used. To drive the device from an external clock source, XTAL2 should be left unconnected while XTAL1 is driven as shown in Figure 6.2.4.There are no requirements on the duty cycle of the external clock signal, since the input to the internal clocking circuitry is through a divide-by-two flipflop, but minimum and maximum voltage high and low time specifications must be observed.

Fig 6.2.3 Oscillator Connections Notes:

Fig 6.2.4 External Clock Drive Configuration

1. Under steady state (non-transient) conditions, IOL must be externally limited as follows: Maximum IOL per port pin: 10 mA Maximum IOL per 8-bit port: Port 0: 26 mA Ports 1, 2, 3: 15 mA Maximum total IOL for all output pins: 71 mA

If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test conditions.

2. Minimum VCC for Power-down is 2V. REGISTERS: In the CPU, registers are used to store information temporarily. That information could be a byte of data to be processed, or an address pointing to the data to be fetched. The vast majority of 8051 registers are 8bit registers. In the 8051 there is only one data type: 8bits. The 8bits of a register are shown in the diagram from the MSB (most significant bit) D7 to the LSB (least significant bit) D0. With an 8-bit data type, any data larger than 8bits must be broken into 8-bit chunks before it is processed. Since there are a large number of registers in the 8051, we will concentrate on some of the widely used general-purpose registers and cover special registers in future chapters. D7 D6 D5 D4 D3 D2 D1 D0 The most widely used registers of the 8051 are A (accumulator), B, R0, R1, R2, R3, R4, R5, R6, R7, DPTR (data pointer), and PC (program counter). All of the above registers are 8-bits, except DPTR and the program counter. The accumulator, register A, is used for all arithmetic and logic instructions.

SFRs (Special Function Registers) Among the registers R0-R7 is part of the 128 bytes of RAM memory. What about registers A, B, PSW, and DPTR? Do they also have addresses? The answer is yes. In the 8051, registers A, B, PSW and DPTR are part of the group of registers commonly referred to as SFR (special function registers). There are many special function registers and they are widely used. The SFR can be accessed by the names (which is much easier) or by their addresses. For example, register A has address E0h, and register B has been ignited the address F0H, as shown in table. The following two points should noted about the SFR addresses. 1. The Special function registers have addresses between 80H and FFH. These addresses are above 80H, since the addresses 00 to 7FH are addresses of RAM memory inside the 8051. 2. Not all the address space of 80H to FFH is used by the SFR. The unused locations 80H to FFH are reserved and must not be used by the 8051 programmer. Regarding direct addressing mode, notice the following two points: (a) the address value is limited to one byte, 00-FFH, which means this addressing mode is limited to accessing RAM locations and registers

located inside the 8051. (b) If you examine the l

st

file for an assembly language program, you will see that

the SFR registers names are replaced with their addresses as listed in table. Symbol ACC B PSW SP DPTR DPL DPH P0 P1 P2 P3 IP IE TMOD TCON T2CON T2MOD TH0 TL0 TH1 TL1 TH2 TL2 RCAP2H RCAP2L SCON SBUF PCON Name Accumulator B register Program status word Stack pointer Data pointer 2 bytes Low byte High byte Port0 Port1 Port2 Port3 Interrupt priority control Interrupt enable control Timer/counter mode control Timer/counter control Timer/counter 2 control Timer/counter mode2 control Timer/counter 0high byte Timer/counter 0 low byte Timer/counter 1 high byte Timer/counter 1 low byte Timer/counter 2 high byte Timer/counter 2 low byte T/C 2 capture register high byte T/C 2 capture register low byte Serial control Serial data buffer Power control Address 0E0H 0F0H 0D0H 81H 82H 83H 80H 90H 0A0H 0B0H 0B8H 0A8H 89H 88H 0C8H 0C9H 8CH 8AH 8DH 8BH 0CDH 0CCH 0CBH 0CAH 98H 99H 87H

Table: 8051 Special function register Address A Register (Accumulator)

This is a general-purpose register which serves for storing intermediate results during operating. A number (an operand) should be added to the accumulator prior to execute an instruction upon it. Once an arithmetical operation is preformed by the ALU, the result is placed into the accumulator. If a data should be transferred from one register to another, it must go through accumulator. For such universal purpose, this is the most commonly used register that none microcontroller can be imagined without (more than a half 8051 microcontroller's instructions used use the accumulator in some way).

B Register B register is used during multiply and divide operations which can be performed only upon numbers stored in the A and B registers. All other instructions in the program can use this register as a spare accumulator (A).

During programming, each of registers is called by name so that their exact address is not so important for the user. During compiling into machine code (series of hexadecimal numbers recognized as instructions by the microcontroller), PC will automatically, instead of registers name, write necessary addresses into the microcontroller. R Registers (R0-R7)

This is a common name for the total 8 general purpose registers (R0, R1, and R2 ...R7). Even they are not true SFRs, they deserve to be discussed here because of their purpose. The bank is active when the R registers it includes are in use. Similar to the accumulator, they are used for temporary storing variables and intermediate results. Which of the banks will be active depends on two bits included in the PSW Register. These registers are stored in four banks in the scope of RAM. The following example best illustrates the useful purpose of these registers. Suppose that mathematical operations on numbers previously stored in the R registers should be performed: (R1+R2) - (R3+R4). Obviously, a register for temporary storing results of addition is needed. Everything is quite simple and the program is as follows:

MOV A, R3; Means: move number from R3 into accumulator ADD A, R4; Means: add number from R4 to accumulator (result remains in accumulator) MOV R5, A; Means: temporarily moves the result from accumulator into R5 MOV A, R1; Means: move number from R1 into accumulator ADD A, R2; Means: add number from R2 to accumulator SUBB A, R5; Means: subtract number from R5 (there are R3+R4) 8051 Register Banks and Stack RAM memory space allocation in the 8052 There are 128 bytes of RAM in the 8051. The 128 bytes of RAM inside the 8051 are assigned addresses 00 to7FH. These 128 bytes are divided into three different groups as follows: 1. A total of 32 bytes from locations 00 to 1FH hex are set aside for register banks and the stack. 2. A total of 16 bytes from locations 20 to 2FH hex are set aside for bit-addressable read/write memory. 3. A total of 80 bytes from locations 30H to 7FH are used for read and write storage, or what is normally called Scratch pad. These 80 locations of RAM are widely used for the purpose of storing data and parameters nu 8051 programmers. Register banks in the 8052 A total of 32bytes of RAM are set aside for the register banks and stack. These 32 bytes are divided into 4 banks of registers in which each bank has registers, R0-R7. RAM locations 0 to 7 are set aside for bank 0 of R0-R7 where R0 is RAM location 0, R1 is RAM location 1, and R2 is location 2, and so on, until memory location7, which belongs to R7 of bank0. The second bank of registers R0-R7 starts at RAM location 08 and goes to location 0FH. The third bank of R0-R7 starts at memory location 10H and goes to location 17H. Finally, RAM locations 18H to 1FH are set aside for the fourth bank of R0-R7. Fig shows how the 32 bytes are allocated into 4 banks. As we can see from fig 1, the bank 1 uses the same RAM space as the stack. This is a major problem in programming the 8052. we must either not use register bank1, or allocate another area of RAM for the stack. Default register bank If RAM locations 00-1F are set aside for the four register banks, which register bank of R0-R7 do we have access to when the 8051 is powered up? The answer is register bank 0; that is , RAM locations 0, 1,2,3,4,5,6, and 7 are accessed with the names R0, R1, R2, R3, R4, R5, R6, and R7 when programming the

8051. It is much easier to refer to these RAM locations with names such as R0, R1 and so on, than by their memory locations as shown in fig 2. The register banks are switched by using the D3 & D4 bits of register PSW.

FIG: RAM Allocation in the 8052

Fig:

8052 Register Banks and their RAM Addresses

PSW Register (Program Status Word)

This is one of the most important SFRs. The Program Status Word (PSW) contains several status bits that reflect the current state of the CPU. This register contains: Carry bit, Auxiliary Carry, two register bank select bits, Overflow flag, parity bit, and user-definable status flag. The ALU automatically changes some of registers bits, which is usually used in regulation of the program performing. P - Parity bit. If a number in accumulator is even then this bit will be automatically set (1), otherwise it will be cleared (0). It is mainly used during data transmission and receiving via serial communication. - Bit 1. This bit is intended for the future versions of the microcontrollers, so it is not supposed to be here. OV Overflow occurs when the result of arithmetical operation is greater than 255 (decimal), so that it can not be stored in one register. In that case, this bit will be set (1). If there is no overflow, this bit will be cleared (0). RS0, RS1 - Register bank selects bits. These two bits are used to select one of the four register banks in RAM. By writing zeroes and ones to these bits, a group of registers R0-R7 is stored in one of four banks in RAM. RS1 0 0 1 1 RS2 0 1 0 1 Space in RAM Bank0 00h-07h Bank1 08h-0Fh Bank2 10h-17h Bank3 18h-1Fh

F0 - Flag 0. This is a general-purpose bit available to the user. AC - Auxiliary Carry Flag is used for BCD operations only. CY - Carry Flag is the (ninth) auxiliary bit used for all arithmetical operations and shift instructions. DPTR Register (Data Pointer) These registers are not true ones because they do not physically exist. They consist of two separate registers: DPH (Data Pointer High) and (Data Pointer Low). Their 16 bits are used for external memory addressing. They may be handled as a 16-bit register or as two independent 8-bit registers. Besides, the DPTR Register is usually used for storing data and intermediate results which have nothing to do with memory locations.

SP Register (Stack Pointer)

The stack is a section of RAM used by the CPU to store information temporarily. This information could be data or an address. The CPU needs this storage area since there are only a limited number of registers. How stacks are accessed in the 8052 If the stack is a section of RAM, there must be registers inside the CPU to point to it. The register used to access the stack is called the SP (Stack point) Register. The stack pointer in the 8052 is only 8 bits wide; which means that it can take values of 00 to FFH. When the 8052 is powered up, the SP register contains value 07. This means that RAM location 08 is the first location used for the stack by the 8051. The storing of a CPU register in the stack is called a PUSH, and pulling the contents off the stack back into a CPU register is called a POP. In other words, a register is pushed onto the stack to save it and popped off the stack to retrieve it. The job of the SP is very critical when push and pop actions are performed. Pushing onto the stack In the 8051 the stack pointer (SP) points to the last used location of the stack. As we push data onto the stack, the stack pointer is incremented by one. Notice that this different from many microprocessors, notably x86 processors in which the SP is decremented when data is pushed onto the stack. As each PUSH is executed, the contents of the register are saved on the stack and SP is incremented by 1. Notice that for every byte of data saved on the stack and then SP is incremented only once. Notice also that to push the registers onto the stack we must use their RAM addresses. For example, the instruction PUSH pushes register R1 onto the stack. Popping from the stack

Popping the contents of the stack back into a given register is the opposite process of pushing. With every pop, the top byte of the stack is copied to the register specified by the instruction and the stack pointer is decremented once. The upper limit of the stack As, mentioned earlier, locations 08 to 1FH in the 8051 RAM can be used for the stack. This is because locations 20-2FH of RAM are reserved for bit-addressable memory and must not be used by the stack. If in a program we need more than 24 bytes (08 to 1FH=24bytes) of stack, we can change the SP to point to RAM locations 30-7FH. This is done with the instruction MOV SP, #XX. P0, P1, P2, P3 - Input/Output Registers

In case that external memory and serial communication system are not in use then, 4 ports with in total of 32 input-output lines are available to the user for connection to peripheral environment. Each bit inside these ports corresponds to the appropriate pin on the microcontroller. This means that logic state written to these ports appears as a voltage on the pin (0 or 5 V). Naturally, while reading, the opposite occurs voltage on some input pins is reflected in the appropriate port bit. The state of a port bit, besides being reflected in the pin, determines at the same time whether it will be configured as input or output. If a bit is cleared (0), the pin will be configured as output. In the same manner, if a bit is set to 1 the pin will be configured as input. After reset, as well as when turning the microcontroller ON, all bits on these ports are set to one (1). This means that the appropriate pins will be configured as inputs. Program counter: The important register in the 8051 is the PC (Program counter). The program counter points to the address of the next instruction to be executed. As the CPU fetches the OPCODE from the program ROM, the program counter is incremented to point to the next instruction. The program counter in the 8051 is 16bits wide. This means that the 8051 can access program addresses 0000 to FFFFH, a total of 64k bytes of code. However, not all members of the 8051 have the entire 64K bytes of on-chip ROM installed, as we will see soon.

Types of instructions Depending on operation they perform, all instructions are divided in several groups:

Arithmetic Instructions Branch Instructions Data Transfer Instructions Logical Instructions Logical Instructions with bits

The first part of each instruction, called MNEMONIC refers to the operation an instruction performs (copying, addition, logical operation etc.). Mnemonics commonly are shortened form of name of operation being executed. For example: INC LJMP LAB5 as LOOP) Another part of instruction, called OPERAND is separated from mnemonic at least by one empty space and defines data being processed by instructions. Some instructions have no operand; some have one, two or three. If there is more than one operand in instruction, they are separated by comma. For example: RET - (return from sub-routine) JZ TEMP - (if the number in the accumulator is not 0, jump to address specified as TEMP) ADD A,R3 - (add R3 and accumulator) CJNE A,#20,LOOP - (compare accumulator with 20. If they are not equal, jump to address specified as LOOP) Arithmetic instructions These instructions perform several basic operations (addition, subtraction, division, multiplication etc.) After execution, the result is stored in the first operand. For example: ADD A, R1 - The result of addition (A+R1) will be stored in the accumulator. R1; ;Long Increment Jump LAB5 R1 (long jump (increment to address register specified as R1) LAB5)

JNZ LOOP ;Jump if Not Zero LOOP (if the number in the accumulator is not 0, jump to address specified

Arithmetical Instructions Mnemonic Description Byte Number Oscillator Period

ADD A,Rn ADD A,Rx ADD A,@Ri ADD A,#X

Add R Register to accumulator Add directly addressed Rx Register to accumulator Add indirectly addressed Register to accumulator Add number X to accumulator

1 2 1 2

1 2 1 2 1

ADDC A,Rn Add R Register with Carry bit to accumulator 1 Branch Instructions There are two kinds of these instructions:

Unconditional jump instructions: After their execution a jump to a new location from where the program continues execution is executed. Conditional jump instructions: If some condition is met - a jump is executed. Otherwise, the program normally proceeds with the next instruction. Branch Instruction Mnemonic ACALL adr11 LCALL adr16 RET RETI AJMP adr11 LJMP adr16 Description Call subroutine located at address within 2 K byte Program Memory space Call subroutine located at any address within 64 K byte Program Memory space Return from subroutine Return from interrupt routine Jump to address located within 2 K byte Program Memory space Jump to any address located within 64 K byte Program Memory space Byte Number 2 3 1 1 2 3 Oscillator Period 3 4 4 4 3 4

Data Transfer Instructions These instructions move the content of one register to another one. The register which content is moved remains unchanged. If they have the suffix X (MOVX), the data is exchanged with external memory.

Data Transfer Instruction Mnemonic MOV A,Rn MOV A,Rx MOV A,@Ri MOV A,#X Description Move R register to accumulator Move directly addressed Rx register to accumulator Move indirectly addressed register to accumulator Move number X to accumulator Byte Number 1 2 1 2 Cycle Number 1 2 1 2

Logical Instructions These instructions perform logical operations between corresponding bits of two registers. After execution, the result is stored in the first operand. Logical Instructions Mnemonic ANL A,Rn ANL A,Rx ANL A,@Ri ANL A,#X Description Logical AND between accumulator and R register Logical AND between accumulator and directly addressed register Rx Logical AND between accumulator and indirectly addressed register Logical AND between accumulator and number X Byte Number 1 2 1 2 Cycle Number 1 2 1 2

Logical Operations on Bits Similar to logical instructions, these instructions perform logical operations. The difference is that these operations are performed on single bits. Logical operations on bits Mnemonic CLR C CLR bit SETB C SETB bit CPL C Description Clear Carry bit Clear directly addressed bit Set Carry bit Set directly addressed bit Complement Carry bit Byte Number 1 2 1 2 1 Cycle Number 1 2 1 2 1

CPL bit

Complement directly addressed bit

TIMERS On-chip timing/counting facility has proved the capabilities of the microcontroller for implementing the real time application. These includes pulse counting, frequency measurement, pulse width measurement, baud rate generation, etc,. Having sufficient number of timer/counters may be a need in a certain design application. The 8051 has two timers/counters. They can be used either as timers to generate a time delay or as counters to count events happening outside the microcontroller. Let discuss how these timers are used to generate time delays and we will also discuss how they are been used as event counters.

PROGRAMMING 8052 TIMERS The 8051 has timers: Timer 0 and Timer1.they can be used either as timers or as event counters. Let us first discuss about the timers registers and how to program the timers to generate time delays. BASIC RIGISTERS OF THE TIMER Both Timer 0 and Timer 1 are 16 bits wide. Since the 8051 has an 8-bit architecture, each 16-bit timer is accessed as two separate registers of low byte and high byte. TIMER 0 REGISTERS

The 16-bit register of Timer 0 is accessed as low byte and high byte. the low byte register is called TL0(Timer 0 low byte)and the high byte register is referred to as TH0(Timer 0 high byte).These register can be accessed like any other register, such as A,B,R0,R1,R2,etc.for example, the instruction MOV TL0, #4Fmoves the value 4FH into TL0,the low byte of Timer 0.These registers can also be read like any other register.

TIMER 1 REGISTERS Timer 1 is also 16-bit register is split into two bytes, referred to as TL1 (Timer 1 low byte) and TH1 (Timer 1 high byte).these registers are accessible n the same way as the register of Timer 0. TMOD (timer mode) REGISTER Both timers TIMER 0 and TIMER 1 use the same register, called TMOD, to set the various timer operation modes. TMOD is an 8-bit register in which the lower 4 bits are set aside for Timer 0 and the upper 4 bits for Timer 1.in each case; the lower 2 bits are used to set the timer mode and the upper 2 bits to specify the operation.

MODES: M1, M0: M0 and M1 are used to select the timer mode. There are three modes: 0, 1, 2.Mode 0 is a 13-bit timer, mode 1 is a 16-bit timer, and mode 2 is an 8-bit timer. We will concentrate on modes 1 and 2 since they are the ones used most widely. We will soon describe the characteristics of these modes, after describing the reset of the TMOD register. GATE Gate control when set. The timer/counter is enabled only While the INTx pin is high and the TRx control pin is. Set. When cleared, the timer is enabled. C/T Timer or counter selected cleared for timer operation (Input from internal system clock).set for counter Operation (input TX input pin). M1 M0 M1 0 M0 0 Mode bit 1 Mode bit 0 MODE 0 Operating Mode 13-bit timer mode

8-bit timer/counter THx with TLx as 5 - Bit pre-scaler. 0 1 1 16-bit timer mode 16-bit timer/counters THx with TLx are Cascaded; there is no prescaler 1 0 2 8-bit auto reload 8-bit auto reload timer/counter;THx Holds a value that is to be reloaded into TLx each time it overflows. 1 1 3 Split timer mode.

C/T (clock/timer) This bit in the TMOD register is used to decide whether the timer is used as a delay generator or an event counter. If C/T=0, it is used as a timer for time delay generation. The clock source for the time delay is the crystal frequency of the 8051.this section is concerned with this choice. The timers use as an event counter is discussed in the next section. Serial Communication: Computers can transfer data in two ways: parallel and serial. In parallel data transfers, often 8 or more lines (wire conductors) are used to transfer data to a device that is only a few feet away. Examples of parallel data transfer are printers and hard disks; each uses cables with many wire strips. Although in such cases a lot of data can be transferred in a short amount of time by using many wires in parallel, the distance cannot be great. To transfer to a device located many meters away, the serial method is used. In serial communication, the data is sent one bit at a time, in contrast to parallel communication, in which the data is sent a byte or more at a time. Serial communication of the 8051 is the topic of this chapter. The 8052 has serial communication capability built into it, there by making possible fast data transfer using only a few wires. If data is to be transferred on the telephone line, it must be converted from 0s and 1s to audio tones, which are sinusoidal-shaped signals. A peripheral device called a modem, which stands for modulator/demodulator, performs this conversion. Serial data communication uses two methods, asynchronous and synchronous. The synchronous method transfers a block of data at a time, while the asynchronous method transfers a single byte at a time. In data transmission if the data can be transmitted and received, it is a duplex transmission. This is in contrast to simplex transmissions such as with printers, in which the computer only sends data. Duplex transmissions can be half or full duplex, depending on whether or not the data transfer can be simultaneous. If data is transmitted one way at a time, it is referred to as half duplex. If the data can go both ways at the

same time, it is full duplex. Of course, full duplex requires two wire conductors for the data lines, one for transmission and one for reception, in order to transfer and receive data simultaneously. Asynchronous serial communication and data framing The data coming in at the receiving end of the data line in a serial data transfer is all 0s and 1s; it is difficult to make sense of the data unless the sender and receiver agree on a set of rules, a protocol, on how the data is packed, how many bits constitute a character, and when the data begins and ends. Start and stop bits Asynchronous serial data communication is widely used for character-oriented transmissions, while block-oriented data transfers use the synchronous method. In the asynchronous method, each character is placed between start and stop bits. This is called framing. In the data framing for asynchronous communications, the data, such as ASCII characters, are packed between a start bit and a stop bit. The start bit is always one bit, but the stop bit can be one or two bits. The start bit is always a 0 (low) and the stop bit (s) is 1 (high). Data transfer rate The rate of data transfer in serial data communication is stated in bps (bits per second). Another widely used terminology for bps is baud rate. However, the baud and bps rates are not necessarily equal. This is due to the fact that baud rate is the modem terminology and is defined as the number of signal changes per second. In modems a single change of signal, sometimes transfers several bits of data. As far as the conductor wire is concerned, the baud rate and bps are the same, and for this reason we use the bps and baud interchangeably. The data transfer rate of given computer system depends on communication ports incorporated into that system. For example, the early IBMPC/XT could transfer data at the rate of 100 to 9600 bps. In recent years, however, Pentium based PCS transfer data at rates as high as 56K bps. It must be noted that in asynchronous serial data communication, the baud rate is generally limited to 100,000bps. RS232 Standards To allow compatibility among data communication equipment made by various manufacturers, an interfacing standard called RS232 was set by the Electronics Industries Association (EIA) in 1960. In 1963 it was modified and called RS232A. RS232B AND RS232C were issued in 1965 and 1969, respectively. Today, RS232 is the most widely used serial I/O interfacing standard. This standard is used in PCs and numerous types of equipment. However, since the standard was set long before the advert of the TTL logic family, its input and output voltage levels are not TTL compatible. In RS232, a 1 is represented by -3 to -25V, while a 0 bit is +3 to +25V, making -3 to +3 undefined. For this reason, to connect any RS232 to a microcontroller system we must use voltage converters such as MAX232 to convert the TTL logic levels to the RS232 voltage levels, and vice versa. MAX232 IC chips are commonly referred to as line drivers. RS232 pins RS232 cable is commonly referred to as the DB-25 connector. In labeling, DB-25P refers to the plug connector (male) and DB-25S is for the socket connector (female). Since not all the pins are used in PC

cables, IBM introduced the DB-9 Version of the serial I/O standard, which uses 9 pins only, as shown in table. DB-9 pin connector 12345 6789 (Out of computer and exposed end of cable) Pin Functions: Pin 1 2 3 4 5 6 7 8 9 Description Data carrier detect (DCD) Received data (RXD) Transmitted data (TXD) Data terminal ready(DTR) Signal ground (GND) Data set ready (DSR) Request to send (RTS) Clear to send (CTS) Ring indicator (RI)

Note: DCD, DSR, RTS and CTS are active low pins. The method used by RS-232 for communication allows for a simple connection of three lines: Tx, Rx, and Ground. The three essential signals for 2-way RS-232 Communications are these: TXD: carries data from DTE to the DCE. RXD: carries data from DCE to the DTE SG: signal ground 8051 connection to RS232 The RS232 standard is not TTL compatible; therefore, it requires a line driver such as the MAX232 chip to convert RS232 voltage levels to TTL levels, and vice versa. The interfacing of 8051 with RS232 connectors via the MAX232 chip is the main topic. The 8051 has two pins that are used specifically for transferring and receiving data serially. These two pins are called TXD and RXD and a part of the port 3 group (P3.0 and P3.1). Pin 11 of the 8051 is assigned to TXD and pin 10 is designated as RXD. These pins are TTL compatible; therefore, they require a line driver to make them RS232 compatible. One such line driver is the MAX232 chip.

MAX232 converts from RS232 voltage levels to TTL voltage levels, and vice versa. One advantage of the MAX232 chip is that it uses a +5V power source which, is the same as the source voltage for the 8051. In the other words, with a single +5V power supply we can power both the 8051 and MAX232, with no need for the power supplies that are common in many older systems. The MAX232 has two sets of line drivers for transferring and receiving data. The line drivers used for TXD are called T1 and T2, while the line drivers for RXD are designated as R1 and R2. In many applications only one of each is used.

TXD

RXD TXD

2 3 5

Embedded Controller

RXD GND

MAX 232

CONNECTING C to PC using MAX 232

INTERRUPTS A single microcontroller can serve several devices. There are two ways to do that: INTERRUPTS or POLLING. POLLING: In polling the microcontroller continuously monitors the status of a given device; when the status condition is met, it performs the service .After that, it moves on to monitor the next device until each one is serviced. Although polling can monitor the status of several devices and serve each of them as certain condition are met. INTERRUPTS: In the interrupts method, whenever any device needs its service, the device notifies the microcontroller by sending it an interrupts signal. Upon receiving an interrupt signal, the microcontroller

interrupts whatever it is doing and serves the device. The program associated with the interrupts is called the interrupt service routine (ISR).or interrupt handler.

INTERRUPTS Vs POLLING:

The advantage of interrupts is that the microcontroller can serve many devices (not all the same time, of course); each device can get the attention of the microcontroller based on the priority assigned to it. The polling method cannot assign priority since it checks all devices in round-robin fashion. More importantly, in the interrupt method the microcontroller can also ignore (mask) a device request for service. This is again not possible with the polling method. The most important reason that the interrupt method is preferable is that the polling method wastes much of the microcontrollers time by polling devices that do not need service. So, in order to avoid tying down the microcontroller, interrupts are used.

INTERRUPT SERVICE ROUTINE For every interrupt, there must be an interrupt service routine (ISR), or interrupt handler. When an interrupt is invoked, the microcontroller runs the interrupts service routine. For every interrupt, there is a fixed location in memory that holds the address of its ISR. The group of memory location set aside to hold the addresses of ISR and is called the Interrupt Vector Table. Shown below: Interrupt Vector Table for the 8051: S.No. INTERRUPT ROM LOCATION (HEX) 0000 0003 PIN FLAG CLEARING 9 P3.2 (12) Auto Auto

1. 2.

Reset External hardware Interrupt 0 Timers 0 interrupt (TF0) External

3. 4.

000B 0013 P3.3 (13)

Auto Auto

hardware Interrupt 1(INT1) 5. 6. Timers 1 interrupt (TF1) Serial COM (RI and TI) 001B 0023 Auto Programmer clears it

Six Interrupts in the 8052: In reality, only five interrupts are available to the user in the 8051, but many manufacturers data sheets state that there are six interrupts since they include reset .the six interrupts in the 8051 are allocated as above. 1. Reset. When the reset pin is activated, the 8051 jumps to address location 0000.this is the power-up reset. 2. Two interrupts are set aside for the timers: one for Timer 0 and one for Timer 1.Memory location 000BH and 001BH in the interrupt vector table belong to Timer 0 and Timer 1, respectively. 3. Two interrupts are set aside for hardware external harder interrupts. Pin number 12(P3.2) and 13(P3.3) in port 3 are for the external hardware interrupts INT0 and INT1,respectively.These external interrupts are also referred to as EX1 and EX2.Memory location 0003H and 0013H in the interrupt vector table are assigned to INT0 and INT1, respectively. 4. Serial communication has a single interrupt that belongs to both receive and transmit. The interrupt vector table location 0023H belongs to this interrupt.

Notice that a limited number of bytes are set aside for each interrupt. For example, a total of 8 bytes from location 0003 to 000A is set aside for INT0, external hardware interrupt 0.similarly,a total of 8 bytes from location 00BH to 0012H is reserved for TF0, Timer 0 interrupt. If the service routine for a given interrupt is short enough to fit in the memory space allocated to it, it is placed in the vector table; otherwise, and an LJMP instruction is placed in the vector table to point to the address of the ISR. In that rest of the bytes allocated to that interrupt are unused. From the above table also notice that only three bytes of ROM space are assigned to the reset pin. they are ROM address location 0,1 and2.address location 3 belongs to external hardware interrupt 0.for this reason, in our program we put the LJMP as the first instruction and redirect the processor away from the interrupt vector table, as shown below Steps in executing an interrupt Upon activation of an interrupt, the microcontroller goes through the following steps.

1. It finishes the instruction it is executing and saves the address of the next instruction (PC) on the stack. 2. It also saves the current status of all the interrupts internally (i.e., not on the stack). 3. It jumps to a fixed location in memory called the interrupt vector table that holds the address of the interrupts service routine. 4. The microcontroller gets the address of the ISR from the interrupt vector table and jumps to it. It starts to execute the interrupt service subroutine until it reaches the last instruction of the subroutine, which is RETI (return from interrupt). 5. Upon executing the RETI instruction, the microcontroller returns to the place where it was interrupted. First, it gets the program counter (PC) address from the stack by popping the top two bytes of the stack into the PC. Then it starts to execute from that address. Notice from step 5 the critical role of the stack. For this reason, we must be careful in manipulating the stack contents in the ISR. Specifically, in the ISR, just as in any CALL subroutine, the number of pushes and pops must be equal. Enabling and disabling an interrupt: Upon reset, all interrupt are disabled (masked), meaning that none will be responded to by the microcontroller if they are activated. The interrupt must be enabled by software in order for the microcontroller to respond to them. There is a register called IE (interrupt enable) that is responsible for enabling (unmasking) and disabling (masking) the interrupts. Notice that IE is a bit-addressable register. Steps in enabling an interrupt: To enable an interrupt, we take the following steps: 1. Bit D7 of the IE register (EA) must be set to high to allow the reset to take effect. If EA=1, interrupts are enabled and will be responded to if their corresponding bit in IE are high. If EA=0, no interrupt will be responded to, even if the associated bit in the IE register is high. Interrupt Enable Register D7 EA D6 -D5 ET2 D4 ES D3 ET1 D2 EX1 D1 ET0 D0 EX0

EA

IE.7

disables all interrupts. If EA=0, no interrupts is acknowledged. If EA=1, each interrupt source is individually enabled disabled By setting or clearing its enable bit.

-ET2 ES ET1 EX1 ET0 EX0

IE.6 IE.5 IE.4 IE.3 IE.2 IE.1 IE.0

Not implemented, reserved for future use.* Enables or disables Timer 2 overflow or capture interrupt (8052 Only) Enables or disables the serial port interrupts. Enables or disables Timers 1 overflow interrupt Enables or disables external interrupt 1. Enables or disables Timer 0 overflow interrupt. Enables or disables external interrupt. 7.3 LCD Display

Liquid crystal displays (LCDs) have materials which combine the properties of both liquids and crystals. Rather than having a melting point, they have a temperature range within which the molecules are almost as mobile as they would be in a liquid, but are grouped together in an ordered form similar to a crystal. An LCD consists of two glass panels, with the liquid crystal material sand witched in between them. The inner surface of the glass plates are coated with transparent electrodes which define the character, symbols or patterns to be displayed polymeric layers are present in between the electrodes and the liquid crystal, which makes the liquid crystal molecules to maintain a defined orientation angle. One each polarisers are pasted outside the two glass panels. These polarisers would rotate the light rays passing through them to a definite angle, in a particular direction When the LCD is in the off state, light rays are rotated by the two polarisers and the liquid crystal, such that the light rays come out of the LCD without any orientation, and hence the LCD appears transparent. When sufficient voltage is applied to the electrodes, the liquid crystal molecules would be aligned in a specific direction. The light rays passing through the LCD would be rotated by the polarisers, which would result in activating / highlighting the desired characters. The LCDs are lightweight with only a few millimeters thickness. Since the LCDs consume less power, they are compatible with low power electronic circuits, and can be powered for long durations.

The LCD s doesnt generate light and so light is needed to read the display. By using backlighting, reading is possible in the dark. The LCDs have long life and a wide operating temperature range. Changing the display size or the layout size is relatively simple which makes the LCDs more customer friendly. The LCDs used exclusively in watches, calculators and measuring instruments are the simple sevensegment displays, having a limited amount of numeric data. The recent advances in technology have resulted in better legibility, more information displaying capability and a wider temperature range. These have resulted in the LCDs being extensively used in telecommunications and entertainment electronics. The LCDs have even started replacing the cathode ray tubes (CRTs) used for the display of text and graphics, and also in small TV applications. This section describes the operation modes of LCDs then describe how to program and interface an LCD to 8051 using Assembly and C.

LCD operation: In recent years the LCD is finding widespread use replacing LED s (sevensegment LED s or other multi-segment LED s).This is due to the following reasons: 1. The declining prices of LCDs. 2. The ability to display numbers, characters and graphics. This is in contrast to LED which is limited to numbers and a few characters. 3. Incorporation of a refreshing controller into the LCD, there by relieving the CPU of the task of refreshing the LCD. In the case of LED s, they must be refreshed by the CPU to keep on displaying the data. 4. Ease of programming for characters and graphics. LCD pin description: The LCD discussed in this section has 14 pins. The function of each pin is given in table.

TABLE 1: Pin description for LCD Pin 1 2 3 4 symbol Vss Vcc VEE RS I/O ---I Description Ground +5V power supply Power supply to control contrast RS=0 to select command register RS=1 to select 5 6 7 8 9 10 11 12 13 14 R/W E DB0 DB1 DB2 DB3 DB4 DB5 DB6 DB7 I I/O I/O I/O I/O I/O I/O I/O I/O I/O data register R/W=0 for write R/W=1 for read Enable The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus The 8-bit data bus

The LCD can display a character successfully by placing the 1. Data in Data Register

2. Command in Command Register of LCD 1. Data corresponds to the ASCII value of the character to be printed. This can be done by placing the ASCII value on the LCD Data lines and selecting the Data Register of the LCD by selecting the RS (Register Select) pin. 2. Each and every display location is accessed and controlled by placing respective command on the data lines and selecting the Command Register of LCD by selecting the (Register Select) RS pin. The commonly used commands are shown below with their operations. TABLE 2: LCD Command Codes Code (hex) 1 2 4 6 5 7 8 A C E F 10 14 18 1C 80 C0 38 Uses: Command to LCD Instruction Register Clear display screen Return home Decrement cursor Increment cursor Shift display right Shift display left Display off, cursor off Display off, cursor on Display on, cursor off Display on, cursor on Display on, cursor blinking Shift cursor position to left Shift cursor position to right Shift the entire display to the left Shift the entire display to the right Force cursor to beginning of 1st line Force cursor to beginning of 2nd line 2 lines and 5x7 matrix The LCDs used exclusively in watches, calculators and measuring instruments are the simple

seven-segment displays, having a limited amount of numeric data. The recent advances in technology have resulted in better legibility, more information displaying capability and a wider temperature range. These have resulted in the LCDs being extensively used in telecommunications and entertainment electronics. So in this project, the LCD is used to display the instantaneous information. The information may be prompting or alerting or instructing the user. 7.4 LINEAR KEYPAD This section basically consists of a Linear Keypad. Basically a Keypad can be classified into 2 categories. One is Linear Keypad and the other is Matrix keypad.

1. Matrix Keypad. 2. Linear Keypad. 1. Matrix Keypad: This Keypad got keys arranged in the form of Rows and Columns. That is why the name Matrix Keypad. According to this keypad, In order to find the key being pressed the keypad need to be scanned by making rows as i/p and columns as output or vice versa. This Keypad is used in places where one needs to connect more no. of keys with less no. of data lines. 2. Linear Keypad: This Keypad got n no. of keys connected to n data lines of microcontroller. This Keypad is used in places where one needs to connect less no. of keys. In this project, Linear Keypad is used with 3 switches being connected because the no. of switches is less (less than 8). Generally, in Linear Keypads one end of the switch is connected to Microcontroller (Configured as i/p) and other end of the switch is connected to the common ground. So whenever a key of Linear Keypad is pressed the logic on the microcontroller pin will go LOW. Here in this project, a linear keypad is used with switches connected in a serial manner. Linear keypad is used in this project because it takes less no. of port pins. shown below. The Linear Keypad with 4 Keys is

7.5 BUZZER: A buzzer or beeper is an audio signaling device, which may be mechanical, electromechanical, or electronic. Typical uses of buzzers and beepers include alarms, timers and confirmation of user input such as a mouse click or keystroke. Mechanical

A joy buzzer is an example of a purely mechanical buzzer. Electromechanical Early devices were based on an electromechanical system identical to an electric bell without the metal gong. Similarly, a relay may be connected to interrupt its own actuating current, causing the contacts to buzz. Often these units were anchored to a wall or ceiling to use it as a sounding board. The word "buzzer" comes from the rasping noise that electromechanical buzzers made. Electronic

Piezoelectric disk beeper A piezoelectric element may be driven by an oscillating electronic circuit or other audio signal source. Sounds commonly used to indicate that a button has been pressed are a click, a ring or a beep. Uses

Annunciator panels Electronic metronomes Game shows :In game shows it is also known as a "lockout system" because when one person signals ("buzzes in"), all others are locked out from signalling. Several game shows have large buzzer buttons which are identified as "plungers". The buzzer is also used to signal wrong answers and when time expires on many game shows. Microwave ovens and other household appliances Sporting events such as basketball games

Symbol

Piezo Buzzer

Advanced Acoustic Technology Corp. professionally manufactures and sells all kinds of buzzers. We have two production lines: piezo buzzer and magnetic buzzer, both include the self drive type, external drive type and SMD type. (Magnetic Buzzer, Transducer, Mechancial Buzzer, Beeper, Piezo Element, Buzzer, Transducer, Piezo Siren, Alarm.) There are over one thousand specifications now, the complete dimensions for you to choose, we can modify the length of the pins and the wires, or even customize for your unique project. Introduction of Piezo Buzzer - How to choose a buzzer

7.6Metal detector

A U.S. Army soldier uses a metal detector to search for weapons and ammunition in Iraq A metal detector is a device which responds to metal that may not be readily apparent.

The simplest form of a metal detector consists of an oscillator producing an alternating current that passes through a coil producing an alternating magnetic field. If a piece of electrically conductive metal is close to the coil, eddy currentswill be induced in the metal, and this produces an alternating magnetic field of its own. If another coil is used to measure the magnetic field (acting as amagnetometer), the change in the magnetic field due to the metallic object can be detected. The first industrial metal detectors were developed in the 1960s and were used extensively for mining and other industrial applications. Uses include de-mining(the detection of land mines), the detection of weapons such as knives and guns, especially in airport security, geophysical prospecting, archaeology and treasure hunting. Metal detectors are also used to detect foreign bodies in food, and in theconstruction industry to detect steel reinforcing bars in concrete and pipes and wires buried in walls and floors. History and development Toward the end of the 19th century, many scientists and engineers used their growing knowledge of electrical theory in an attempt to devise a machine which would pinpoint metal. The use of such a device to find ore-bearing rocks would give a huge advantage to any miner who employed it. The German physicist Heinrich Wilhelm Dove invented the induction balance system, which was incorporated into metal detectors a hundred years later. Early machines were crude, used a lot of battery power, and worked only to a very limited degree.Alexander Graham Bell used such a device to attempt to locate a bullet lodged in the chest of American President James Garfield in 1881; the attempt was unsuccessful because the metal coil spring bed Garfield was lying on confused the detector. Modern developments The modern development of the metal detector began in the 1930s. Gerhard Fisher had developed a system of radio direction-finding, which was to be used for accurate navigation. The system worked extremely well, but Fisher noticed that there were anomalies in areas where the terrain contained ore-bearing rocks. He reasoned that if a radio beam could be distorted by metal, then it should be possible to design a machine which would detect metal using a search coil resonating at a radio frequency. In 1937 he applied for, and was granted, the first patent for a metal detector. However, it was one Lieutenant Jozef Stanislaw Kosacki, a Polish officer attached to a unit stationed in St Andrews, Fife, Scotland during the early years of World War II, that refined the design into a practical Polish mine detector. They were heavy, ran on vacuum tubes, and needed separate battery packs. The design invented by Kosacki was used extensively during the clearance of the German mine fields during the Second Battle of El Alamein when 500 units were shipped to Field Marshal Montgomery to clear the minefields of the retreating Germans, and later used during the Allied invasion of Sicily, the Allied invasion of Italy and the Invasion of Normandy. As it was a wartime research operation to create and refine the design of the detector, the knowledge that Stanislaw created the first practical metal detector was kept secret for over 50 years. After the war, there were plenty of surplus mine detectors on the market; they were bought up by relic hunters who used them for fun and profit. This helped to form metal detecting into a hobby.

Further refinements Many manufacturers of these new devices brought their own ideas to the market. Whites Electronics of Oregon began in the 50's by building a machine called the Oremaster Geiger Counter. Another leader in detector technology was Charles Garrett, who pioneered the BFO (Beat Frequency Oscillator) machine. With the invention and development of the transistor in the 50's and 60's, metal detector manufacturers and designers made smaller lighter machines with improved circuitry, running on small battery packs. Companies sprang up all over the USA and Britain to supply the growing demand. Modern top models are fully computerized, using integrated circuit technology to allow the user to set sensitivity, discrimination, track speed, threshold volume, notch filters, etc., and hold these parameters in memory for future use. Compared to just a decade ago, detectors are lighter, deeper-seeking, use less battery power, and discriminate better. Larger portable metal detectors are used by archaeologists and treasure hunters to locate metallic items, such as jewelry, coins, bullets, and other various artifacts buried shallowly underground. Discriminators The biggest technical change in detectors was the development of the induction-balance system. This system involved two coils that were electrically balanced. When metal was introduced to their vicinity, they would become unbalanced. What allowed detectors to discriminate between metals was the fact that every metal has a different phase response when exposed to alternating current. Scientists had long known of this fact by the time detectors were developed that could selectively detect desirable metals, while ignoring undesirable ones. Even with discriminators, it was still a challenge to avoid undesirable metals, because some of them have similar phase responses e.g. tinfoil and gold, particularly in alloy form. Thus, improperly tuning out certain metals increased the risk of passing over a valuable find. Another disadvantage of discriminators was that they reduced the sensitivity of the machines. New coil designs Coil designers also tried out innovative designs. The original Induction Balance coil system consisted of two identical coils placed on top of one another. Compass Electronics produced a new design; the two coils were made in a D shape, and were mounted back-to-back to form a circle. This system was widely used in the 1970s, and both concentric and D type (or Widescan as they became known) had their fans. Another development was the invention of detectors which could cancel out the effect of mineralization in the ground. This gave greater depth, but was a non-discriminate mode. It worked best at lower frequencies than those used before, and frequencies of 3 to 20 kHz were found to produce the best results. Many detectors in the 1970s had a switch which enabled the user to switch between the discriminate mode and the nondiscriminate mode. Later developments switched electronically between both modes. The development of the Induction Balance detector would ultimately result in the Motion detector, which constantly checked and balanced the background mineralization.

Pulse induction

A pulse induction metal detector with an array of coils At the same time, developers were looking at using a different technique in metal detection called Pulse Induction. Unlike the Beat Frequency Oscillator or the Induction Balance machines which both used a uniform alternating current at a low frequency, the pulse induction machine simply fired a high-voltage pulse of signal into the ground. In the absence of metal, the 'spike' decayed at a uniform rate, and the time it took to fall to zero volts could be accurately measured. However, if metal was present when the machine fired, a small current would flow in the metal, and the time for the voltage to drop to zero would be increased. These time differences were minute, but the improvement in electronics made it possible to measure them accurately and identify the presence of metal at a reasonable distance. These new machines had one major advantage: they were completely impervious to the effects of mineralization, and rings and other jewellery could now be located even under highly-mineralized black sand. Uses Archaeology In England and Wales metal detecting is legal provided that permission is granted by the landowner, and that the area is not a Scheduled Ancient Monument a site of special scientific interest (SSSI) or covered by elements of the Countryside Stewardship Scheme. Items discovered which fall within the definition of Treasure must be reported to the Coroner or a place designated by the Coroner for Treasure. The voluntary reporting of finds which do not qualify as Treasure to the Portable Antiquities Scheme or the UK Detector Finds Database is encouraged. The situation in Scotland is very different. Under the Scots law principle of bona vacantia, the Crown has claim over any object of any material value where the original owner cannot be traced.There is also no 300 year limit to Scottish finds. Any artifact found, whether by metal detector survey or from an archaeological excavation, must be reported to the Crown through the Treasure Trove Advisory Panel at the National Museums of Scotland. The Panel then determines what will happen to the artifacts. Reporting is not voluntary, and failure to report the discovery of historic artifacts is a criminal offence in Scotland.

As a hobby

This 156 ounce nugget was found by an individual prospector in the Southern California Desert using a metal detector There are six major types of hobbyist activities involving metal detectors:

Coin shooting is looking for coins after an event involving many people, like a baseball game, or simply looking for any old coins. Serious coin shooters will spend hours, days and months doing historical research to locate long lost sites that have the potential to give up historical and collectible coins. Prospecting is looking for valuable metals like gold and silver in their natural forms, such as nuggets or flakes. Relic hunting is very similar to coin shooting except that the relic hunter is after any type of historical artifact. Relic hunters are usually very determined and dedicated not only to the research and hunting that they do but also to preserving historical artifacts. Coins, bullets, buttons, axe heads, and buckles are just a few of the items that are commonly found by relic hunters. Treasure hunting is looking for valuable items in general. Beach combing is hunting for lost coins or jewelry on a beach. Beach hunting can be as simple or as complicated as one wishes to make it. Many dedicated beach hunters also familiarize themselves with tide movements and beach erosion. Metal detecting clubs across the United States, United Kingdom and Canada exist for hobbyists to learn from others, show off finds from their hunts and to learn more about the hobby.

Security screening

Metal detectors at an airport A series of aircraft hijackings led the Finnish company Outokumpu to adapt mining metal detectors,still housed in a large cylindrical pipe, to the purpose of screening airline passengers as they walked through.

The development of these systems continued in a spin off company and systems branded as Metor Metal Detectors evolved in the form of the rectangular gantry now standard in airports. In common with the developments in other uses of metal detectors both alternating current and pulse systems are used, and the design of the coils and the electronics has moved forward to improve the discrimination of these systems. In 1995 systems such as the Metor 200 appeared with the ability to indicate the approximate height of the metal object above the ground, enabling security personnel to more rapidly locate the source of the signal. Smaller hand held metal detectors are also used to locate a metal object on a person more precisely. Industrial metal detectors Industrial metal detectors are used in the pharmaceutical, food, beverage, textile, plastics, chemicals, lumber, and packaging industries. Contamination of food by metal shards from broken processing machinery during manufacture is a major safety issue in the food industry. Metal detectors for this purpose are widely used and integrated in the production line. Civil engineering In civil engineering special metal detectors (cover meters) are used to locate rebars. Rebar detectors are less sophisticated devices that can only locate metallic objects below the surface.

7.7 H BRIDGE:

Structure of an H-bridge (highlighted in red) An H-bridge is an electronic circuit which enables a voltage to be applied across a load in either direction. These circuits are often used in robotics and other applications to allow DC motors to run forwards and backwards. H-bridges are available as integrated circuits, or can be built from discrete components. General The term "H-bridge" is derived from the typical graphical representation of such a circuit. An H-bridge is built with four switches (solid-state or mechanical). When the switches S1 and S4 (according to the first figure) are closed (and S2 and S3 are open) a positive voltage will be applied across the motor. By opening S1 and S4 switches and closing S2 and S3 switches, this voltage is reversed, allowing reverse operation of the motor.

Using the nomenclature above, the switches S1 and S2 should never be closed at the same time, as this would cause a short circuit on the input voltage source. The same applies to the switches S3 and S4. This condition is known as shoot-through. Operation

The two basic states of an H-bridge. The H-Bridge arrangement is generally used to reverse the polarity of the motor, but can also be used to 'brake' the motor, where the motor comes to a sudden stop, as the motor's terminals are shorted, or to let the motor 'free run' to a stop, as the motor is effectively disconnected from the circuit. The following table summarizes operation. S1 1 0 0 0 1 S2 S3 S4 Result 0 0 1 Motor moves right 1 1 0 Motor moves left 0 0 0 Motor free runs 1 0 1 Motor brakes 0 1 0 Motor brakes

(S1-4 reference to the above diagrams) Construction

Typical solid state H-bridge A solid-state H-bridge is typically constructed using reverse polarity devices (i.e., PNP BJTs or P-channel MOSFETs connected to the high voltage bus and NPN BJTs or N-channel MOSFETs connected to the low voltage bus). The most efficient MOSFET designs use N-channel MOSFETs on both the high side and low side because they typically have a third of the ON resistance of P-channel MOSFETs. This requires a more complex design since the gates of the high side MOSFETs must be driven positive with respect to the DC supply rail. However, many integrated circuit MOSFET drivers include a charge pump within the device to achieve this. Alternatively, a switch-mode DC-DC converter can be used to provide isolated ('floating') supplies to the gate drive circuitry. A multiple-output flyback converter is well-suited to this application.

Another method for driving MOSFET-bridges is the use of a specialized transformer known as a GDT (Gate Drive Transformer), which gives the isolated outputs for driving the upper FETs gates. The transformer core is usually a ferrite toroid, with 1:1 or 4:9 winding ratio. However, this method can only be used with high frequency signals. The design of the transformer is also very important, as the leakage inductance should be minimized, or cross conduction may occur. The outputs of the transformer also need to be usually clamped by zener diodes, because high voltage spikes could destroy the MOSFET gates. A common variation of this circuit uses just the two transistors on one side of the load, similar to a class AB amplifier. Such a configuration is called a "half bridge". The half bridge is used in some switched-mode power supplies that use synchronous rectifiers and in switching amplifiers. The half H-bridge type is commonly abbreviated to "Half-H" to distinguish it from full ("Full-H") H-bridges. Another common variation, adding a third 'leg' to the bridge, creates a 3-phase inverter. The 3-phase inverter is the core of any AC motor drive. A further variation is the half-controlled bridge, where one of the high- and low-side switching devices (on opposite sides of the bridge) are replaced with diodes. This eliminates the shoot-through failure mode, and is commonly used to drive variable/switched reluctance machines and actuators where bi-directional current flow is not required. A "double pole double throw" relay can generally achieve the same electrical functionality as an H-bridge (considering the usual function of the device). An H-bridge would be preferable to the relay where a smaller physical size, high speed switching, or low driving voltage is needed, or where the wearing out of mechanical parts is undesirable. Bridge circuit A bridge circuit is a type of electrical circuit in which the current in a conductor splits into two parallel paths and then recombines into a single conductor, thereby enclosing a loop. It was originally used for measurement purposes, but can also be used in power supplies.

Schematic of a Wheatstone bridge The best-known bridge circuit, the Wheatstone bridge, was invented by Samuel Hunter Christie and popularized by Charles Wheatstone, and is used for measuring resistance. It is constructed from four resistors, one of which has an unknown value (Rx), one of which is variable (R2), and two of which are fixed and equal (R1 and R3), connected as the sides of a square. Two opposite corners of the square are connected to a source of electrical current, such as a battery. A galvanometer is connected across the other two opposite corners. The variable resistor is adjusted until the galvanometer reads zero. It is then known that the ratio between the variable resistor and its neighbour is equal to the ratio between the unknown resistor and its neighbour, and this enables the value of the unknown resistor to be calculated.

The Wheatstone bridge has also been developed to measure impedance in AC circuits, resulting in designs such as the Wien bridge, the Maxwell bridge and the Heaviside bridge. All are based on the same principle, which is to compare the output of two potentiometers sharing a common source. In power supply design, a bridge circuit or bridge rectifier is an arrangement of diodes or similar devices used to rectify an electric current, i.e. to convert it from an unknown or alternating polarity to a direct current of known polarity. In some motor controllers, a H-bridge is used to control the direction the motor turns. Gallery

Wheatstone bridge

Bridge T circuit

L293D Dual H-Bridge Motor Driver L293D is a dual H-Bridge motor driver, So with one IC we can interface two DC motors which can be controlled in both clockwise and counter clockwise direction and if you have motor with fix direction of motion the you can make use of all the four I/Os to connect up to four DC motors. L293D has output current of 600mA and peak output current of 1.2A per channel. Moreover for protection of circuit from back EMF ouput diodes are included within the IC. The output supply (VCC2) has a wide range from 4.5V to 36V, which has made L293D a best choice for DC motor driver.

A simple schematic for interfacing a DC motor using L293D is shown below.

As you can see in the circuit, three pins are needed for interfacing a DC motor (A, B, Enable). If you want the o/p to be enabled completely then you can connect Enable to VCC and only 2 pins needed from controller to make the motor work. As per the truth mentioned in the image above its fairly simple to program the microcontroller. Its also clear from the truth table of BJT circuit and L293D the programming will be same for both of them, just keeping in mind the allowed combinations of A and B. We will discuss about programming in C as well as assembly for running motor with the help of a microcontroller.

MOTOR CONTROL Basics of motor control This tutorial introduces the concept of motor control and how H-bridge can be implemented to control the speed of the motor. What is a motor controller? A motor controller is a device or group of devices that serves to govern in some predetermined manner the performance of an electric motor. Unidirectional control

This can be achieved simply by changing the polarity of the applied voltage or a mechanical two way spring loaded switch which also changes the polarity (See Fig. above).

Bi-Directional Or H-bridge control With the help of relays or opto couplers with amplifiers (some specially designed ICs) we can change the direction of the DC motor rotation. Circuits below shows the simple concept behind H-bride control of DC motors.

In Fig.1 simple H-bridge Connection is shown using switch. Where all the switches are open and the motor is not receiving any potential difference V or current I and hence it is not rotating.

In Fig.2 switches S2 and S3 are open and S1 and S4 are closed which creates a potential difference across the motor and simultaneously a current flows through the circuit which rotates the motor shaft, lets say, in the clockwise (CW) direction.

Similarly, in Fig.3 switches S1 and S4 are open and S2 and S3 are closed which rotates the motor in anticlockwise direction.

H-Bridge L293B/D After the basics here comes the real Integrated Circuit (ICs) based H-Bridges which are essentially made by using electronic circuit elements such as opto coupler switches, operational amplifiers and some safety elements. You can also see our tutorial on how to make your own Simple Motor Driver or H-bridge? [Coming Soon] These ICs are also called Motor controllers and come as a single package depending on the desired current and voltage ratings. One of the very common H-bridge ICs available in the market is L293B or L293D. It is in fact a double H-Bridge, since motion of two motors can be simultaneously controlled on each half. While interfacing with Microcontrollers GND (0 V) and voltage supply to the motor is needed in H-Bridge since input is being provided from microcontroller. Additionally H-Bridge can also be used in remote controlled circuits with the only difference being that the inputs provided to the input pins of the H-Bridge (which was earlier being provided by the microcontroller) will now be in the form of external 5V supply for bit 1 (high) and ground (0 V) for bit 0 (low). It is always advised to go through the datasheet of the ICs before using them. There are a lot of manufacturers who sell these ICs, and finding a datasheet is easy. Yet a detailed description of how to use an H-Bridge IC L293D is provided below.

Firstly identify your PINs like IN for input, OUT for output, GND for ground (0 V), EN enable pin for enabling whichever half of the H-Bridge to be used (explained later in detail), Vcc for operating voltage of

ICs generally 5v and lastly +V voltage applied to the motor which should be more than Vcc otherwise ICs would not work properly. (See Fig. 1) Secondly, have a look at the numbering of the pins and try to remember them. Here we have used bit 1(one) and bit 0 (zero) in place of 5V and GND respectively (or simply we will consider our inputs in terms of binary digits 0 and 1). Let us see how L293D works

In Fig.2 a circuit connection has been shown, where M1 & M2 are two DC motors connected to the outputs on each half (pin no 3, 6 & 11, 14) .We can see that Vcc, GND and +V all have fixed potentials. Now we will simultaneously enable the two half with enable pins (1 & 9) by providing logic high i.e. bit 1 or simply value equal to Vcc i.e. 5V , then we try to rotate the motor in the same direction by applying bit 1 & 0 to INPUT pins (2,7 & 15,10). We will observe a potential difference of +V voltage across both the output terminals of M1and M2 (pin no 3,6 & 14,11).

Since we have explained earlier we can change the direction of rotation of the motor by just reversing our INPUT. Lets say, now we have reversed our input for M1 i.e. we are now applying bit 0 & 1 to the input pins (IN1 and IN2). We can see in the circuit that the outputs for M1 has reversed and hence the direction of rotation of the motor (because polarity has been reversed). Similarly the other half can also behave as per your requirements. (See Fig. 3)

Now we will see the role of ENABLE pins (1,2EN & 3,4EN or pin no 1 & 9). In Fig. 4 we have changed the input of 1,2 EN to bit 0 (zero) and the potential difference across M1 output pins is ZERO or nil which tells us that one H-bridge has been disabled and the motor stops rotating. This is basically an additional help to control the motor by just enabling or disabling the required half of L293D IC. Some facts about L293D Hbridge

600-mA Output Current Capability Per Driver Pulsed Current 1.2-A Per Driver Output Clamp Diodes for Inductive Transient Suppression Wide Supply Voltage Range 4.5 V to 36 V Separate Input-Logic Supply Thermal Shutdown Internal ESD Protection High-Noise-Immunity Inputs Functional Replacement for SGS L293D

L293D QUADRUPLE HALF-H DRIVERS

The Device is a monolithic integrated high voltage, high current four channel driver designed to accept standard DTL or TTL logic levels and drive inductive loads (such as relays solenoids, DC and stepping motors) and switching power transistors. To simplify use as two bridges each pair of channels is equipped with an enable input. A separate supply input is provided for the logic, allowing operation at a lower voltage and internal clamp diodes are included. This device is suitable for use in switching applications at frequencies up to 5 kHz.

Ideal for driving DC Motors and Stepper Motors Wide Supply-Voltage Range: 4.5 V to 36 V Separate Input-Logic Supply Internal ESD Protection Thermal Shutdown High-Noise-Immunity Inputs Output Current 1600mA Per Channel Peak Output Current 1.2 A Per Channel Output Clamp Diodes for Inductive Transient Suppression

7.8 DC MOTOR: 5DC MOTOR A DC motor is designed to run on DC electric power. Two examples of pure DC designs are Michael Faraday's homopolar motor (which is uncommon), and the ball bearin motor, which is (so far) a novelty. By far the most common DC motor types are the brushed and brushless types, which use internal and external commutation respectively to create an oscillating AC current from the DC source -- so they are not purely DC machines in a strict sense.

Types of dc motors: 1. Brushed DC Motors 2. Brushless DC motors 3. Coreless DC motors

Brushed DC motors: The classic DC motor design generates an oscillating current in a wound rotor with a split ring commutator, and either a wound or permanent magnet stator. A rotor consists of a coil wound around a rotor which is then powered by any type of battery. Many of the limitations of the classic commutator DC motor are due to the need for brushes to press against the commutator. This creates friction. At higher speeds, brushes have increasing difficulty in maintaining contact. Brushes may bounce off the irregularities in the commutator surface, creating sparks. This limits the maximum speed of the machine. The current density per unit area of the brushes limits the output of the motor. The imperfect electric contact also causes electrical noise. Brushes eventually wear out and require replacement, and the commutator itself is subject to wear and maintenance. The commutator assembly on a large machine is a costly element, requiring precision assembly of many parts. There are three types of dc motor 1. Dc series motor 2. Dc shunt motor 3. Dc compound motor - these are also two type a. cumulative compound b. deffercial compound Brushless DC motors: Some of the problems of the brushed DC motor are eliminated in the brushless design. In this motor, the mechanical "rotating switch" or commutator/brush gear assembly is replaced by an external electronic switch synchronized to the rotor's position. Brushless motors are typically 85-90% efficient, whereas DC motors with brush gear are typically 75-80% efficient. Midway between ordinary DC motors and stepper motors lies the realm of the brushless DC motor. Built in a fashion very similar to stepper motors, these often use a permanent magnet external rotor, three phases of driving coils, one or more Hall effect sensors to sense the position of the rotor, and the associated drive electronics. The coils are activated, one phase after the other, by the drive electronics as cued by the signals from the Hall effect sensors. In effect, they act as three-phase synchronous motors containing their own variable-frequency drive electronics. A specialized class of brushless DC motor controllers utilizes EMF feedback through the main phase connections instead of Hall Effect sensors to determine position and velocity. These motors are used extensively in electric radio-controlled vehicles. When configured with the magnets on the outside, these are referred to by modelists as out runner motors. Brushless DC motors are commonly used where precise speed control is necessary, as in computer disk drives or in video cassette recorders, the spindles within CD, CD-ROM (etc.) drives, and mechanisms within office products such as fans, laser printers and photocopiers. They have several advantages over conventional motors:

Compared to AC fans using shaded-pole motors, they are very efficient, running much cooler than the equivalent AC motors. This cool operation leads to much-improved life of the fan's bearings.

Without a commutator to wear out, the life of a DC brushless motor can be significantly longer compared to a DC motor using brushes and a commutator. Commutation also tends to cause a great deal of electrical and RF noise; without a commutator or brushes, a brushless motor may be used in electrically sensitive devices like audio equipment or computers.

The same Hall effect sensors that provide the commutation can also provide a convenient tachometer signal for closed-loop control (servo-controlled) applications. In fans, the tachometer signal can be used to derive a "fan OK" signal.

The motor can be easily synchronized to an internal or external clock, leading to precise speed control. Brushless motors have no chance of sparking, unlike brushed motors, making them better suited to environments with volatile chemicals and fuels. Also, sparking generates ozone which can accumulate in poorly ventilated buildings risking harm to occupants' health.

Brushless motors are usually used in small equipment such as computers and are generally used to get rid of unwanted heat. They are also very quiet motors which is an advantage if being used in equipment that is affected by vibrations.

Modern DC brushless motors range in power from a fraction of a watt to many kilowatts. Larger brushless motors up to about 100 kW rating are used in electric vehicles. They also find significant use in highperformance electric model aircraft. Coreless DC motors: Nothing in the design of any of the motors described above requires that the iron (steel) portions of the rotor actually rotate; torque is exerted only on the windings of the electromagnets. Taking advantage of this fact is the coreless DC motor, a specialized form of a brush or brushless DC motor. Optimized for rapid acceleration, these motors have a rotor that is constructed without any iron core. The rotor can take the form of a winding-filled cylinder inside the stator magnets, a basket surrounding the stator magnets, or a flat pancake (possibly formed on a printed wiring board) running between upper and lower stator magnets. The windings are typically stabilized by being impregnated with Electrical epoxy potting systems. Filled epoxies that have moderate mixed viscosity and a long gel time. These systems are highlighted by low shrinkage and low exotherm. Typically UL 1446 recognized as a potting compound for use up to 180C (Class H) UL File No. E 210549. Because the rotor is much lighter in weight (mass) than a conventional rotor formed from copper windings on steel laminations, the rotor can accelerate much more rapidly, often achieving a mechanical time constant under 1 ms. this is especially true if the windings use aluminum rather than the heavier copper. But because there is no metal mass in the rotor to act as a heat sink, even small coreless motors must often be cooled by forced air.

These motors were commonly used to drive the capstan(s) of magnetic tape drives and are still widely used in high-performance servo-controlled systems, like radio-controlled vehicles/aircraft, humanoid robotic systems, industrial automation, medical devices, etc.

7.9: ZIGBEE: Objective : To Introduce ZigBee Wireless Technology, show the broad perspective of the applications built upon it, business perspectives of it, technical specifications briefing as per the Zigbee Specs 1.0 standard(2005), its comparison to 2006 Zigbee Specs ,Work in progress with history as in milestones to the specifications and finally show some chips which work are used to implement zigbee technology. An Intro : ZigBee technology is from and patent to Zigbee alliance(a company). ZigBee is a ad-hoc wireless technology implemented through RF radios at 2.4 Mhz(same frequency as Bluetooth which uses frequency hopping spread spectrum) but ZigBee uses Direct sequence spread spectrum like wifi/802.11s. ZigBee is an RF transceiver with DSSS ,it has multiple reflections of the path to reach destination, because of low power limitation ,RF signal is forced to take shortest path and then reflect from there to destination in certain lengths of hops and so different algorithms for hops are designed (hence the word ZigBee from Zigzag path ) It supports networking in most efficient for range and obstruction issues avoidance topologies Mesh and Tree n/ws. It is designed with simple but brick type encryption for security. Smart low cost chips based on technology enable vendors to build applications at customer affordable and innovative applications (control and monitoring). Work in progress : The XBee (A chip from max stream) OEM RF module is a ZigBee compliant , low-cost a $19 chip, low-power 1 mW (0 dBm) power output - up to 100m range, wireless sensor networks ISM 2.4 GHz operating frequency. Is an example of the now available chips in market, which should give us an idea that the technology is well implemented i.e. commercialized and has become ubiquitous to us. ZigBee embedded microcontrollers are in the market which are ideal and easy for application deployment, companies like Jennic, maxstream , Atmel , Microchip, STmicroelectronics ,Renesas technology etc are currently producing and improvising on such chips. ZigBee being a stack for the radio, the other layers can be changed for efficient protocols of communication and bit transfers except mac and physical layers which as per 802.15.4 for WPANs is

fixed, as such the algorithms for security, crc, error corrections are being altered for finding the most efficient ways to deal with , in the field of research. Over the years : ZigBee has evolved in the hands of ZigBee Alliance with miniature modifications for the best. History of Specifications: December 14, 2004 ZigBee v.1.0 draft ratified Version r06: February 17, 2006 ZigBee Specification (ZigBee doc no. 053474r06/07) Version r07: April 28, 2006 Changes made per Editorial comments on spreadsheet, Version r13: December 1, 2006 3:08 pm ZigBee-2006 Specification . huge hall. founder. in the field addressed issues with technical explanations. Evolution Of Low-Rate Wireless Personal Area Network (LR-WPAN) Standardization The Cellular Network Was A Natural Extension Of The Wired Telephony Network That Became Persistent During The Mid-20th Century. As The Need For Mobility And The Cost Of Laying New Wires Increased, The Motivation For A Personal Connection Independent Of Location To That Network Also Increased. Coverage Of Large Area Is Provided Through (1-2km) Cells That Co-Operate With Their Neighbors To Create A Seamless Network. Cellular Standards Basically Aimed At Facilitating Voice Communications Throughout A Metropolitan Area. During The Mid-1980s, It Turned Out That An Even Smaller Coverage Area Is Needed For Higher User Densities And The Emergent Data Traffic. The IEEE 802.11 Working Group For Wireless Local Area Network (WLAN) Is Formed, To Create A Wireless Local Area Network Standard. Whereas IEEE 802.11 Was Concerned With Features Such As Ethernet Matching Speed, Long Range(100m), Complexity To Handle Seamless Roaming, Message Forwarding, And Data Throughput Of 2-11Mbps. Wireless Personal Area Networks (Wpans) Are Used To Convey Information Over Relatively Short Distances. Wpans Are Focused On A Space Around A Person Or Object That Typically Extends Up To 10m In All Directions. The Focus Of Wpans Is Low-Cost, Low Power, Short Range And Very Small Size. The first "We are getting to the world During the packaged ZigBee system made by Freescale, featured a switch that operated from the other side of a of James Bond gadgets," said Jon Adams, director of radio technology at Freescale and a ZigBee ZigBee Conference to be held in Paris on 10 to 13 May 2005 , distinguished experts and key players

The IEEE 802.15 Working Group Is Formed To Create WPAN Standard. This Group Has Currently Defined Three Classes Of Wpans That Are Differentiated By Data Rate, Battery Drain And Quality Of Service (Qos). The High Data Rate WPAN (IEEE 802.15.3) Is Suitable For Multi-Media Applications That Require Very High Quality Of Services. Medium Rate Wpans (IEEE 802.15.1/Bluetooth) Will Handle A Variety Of Tasks Ranging From Cell Phones To PDA Communications And Have Qos Suitable For Voice Communications. Industrial, Residential And Medical Applications With Very Low Power Consumption, With Relaxed Needs For Data Rate And Qos. The Low Data Rate Enables The LR-WPAN To Consume Very Little Power. This Feature Allows Small, Power-Efficient, Inexpensive Solutions To Be Implemented For A Wide Range Of Devices.

7.4.1 Why Is It Called Zigbee? It Has Been Suggested That The Name Evokes The Haphazard Paths That Bees Follow As They Harvest Pollen, Similar To The Way Packets Would Move Through A Mesh Network. Using Communication System, Whereby The Bee Dances In A Zig-Zag Pattern, Worker Bee Is Able To Share Information Such As The Location, Distance, And Direction Of A Newly Discovered Food Source To Her Fellow Colony Members. Instinctively Implementing The Zigbee Principle, Bees Around The World Actively Sustain Productive Itchiness And Promote Future Generations Of Colony Members. Z he Low Rate Wpans (IEEE 802.15.4/LR-WPAN) Is Intended To Serve A Set Of General Description A LR-WPAN Is A Simple, Low-Cost Communication Network That Allows Wireless Connectivity In Applications With Limited Power And Relaxed Throughput Requirements. The Main Objectives Of An LR-WPAN Are Ease Of Installation, Reliable Data Transfer, ShortRange Operation, Extremely Low Cost, And A Reasonable Battery Life, While Maintaining A Simple And Flexible Protocol. The Three License-Free Frequencies Of The IEEE 802.15.4 Standard Include Sixteen Channels At 2.4 Ghz, Ten Channels At 915 Mhz, And One Channel At 868 Mhz, To Support Global Or Regional Deployment. The Maximum Data Rates For Each Band Are 250 Kbps, 40 Kbps And 20 Kbps, Respectively. The Air Interface Is Direct Sequence Spread Spectrum (DSSS) Using Binary Phase Shift Keying (BPSK) For 868 Mhz And 915 Mhz And Offset-Quadrature Phase Shift Keying (OQPSK) For 2.4 Ghz. Other Features Of The IEEE 802.15.4 PHY Include Receiver Energy Detection, Link Quality

Indication And Clear Channel Assessment. Both Contention-Based And Contention-Free Channel Access Methods Are Supported. Maximum Packet Size Is 128 Bytes, Including A Variable Payload Of Up To 104 Bytes. IEEE 802.15.4 Employs 64-Bit IEEE And 16-Bit Short Addresses, Which Supports Over 65,000 Nodes Per Network.

The IEEE 802.15.4 MAC Also Enables Network Association And Disassociation, Has An Optional Super Frame Structure With Beacons For Time Synchronization, And A Guaranteed Time Slot (GTS) Mechanism For High Priority Communications. The Access Method Is Carrier Sense Multiple Access With Collision Avoidance (CSMA-CA). Network Routing Schemes Are Designed To Ensure Power Conservation, And Low Latency Through Guaranteed Time Slots. A Unique Feature Of Zigbee Network Layer Is Communication Redundancy Eliminating Single Point Of Failure In Mesh Networks. IEEE And Zigbee Alliance Have Been Working Closely To Specify The Entire Protocol Stack. IEEE 802.15.4 Focuses On The Specification Of The Lower Two Layers Of The Protocol (Physical And Data Link Layer). On The Other Hand, Zigbee Alliance Aims To Provide The Upper Layers Of The Protocol Stack (From Network To The Application Layer) For Interoperable Data Networking, Security Services And A Range Of Wireless Home And Building Control Solutions. 7.4.2 Zigbee Characteristics The Focus Of Network Applications Under The IEEE 802.15.4 / Zigbee Standard Include The Features Of Low Power Consumption, Needed For Only Two Major Modes (Tx/Rx Or Sleep), High Density Of Nodes Per Network, Low Costs And Simple Implementation. These Features Are Enabled By The Following Characteristics 2.4ghz And 868/915 Mhz Dual PHY Modes. This Represents Three License-Free Bands: 2.4-2.4835 Ghz, 868-870 Mhz And 902928 Mhz. The Number Of Channels Allotted To Each Frequency Band Is Fixed At 16 Channels In The 2.45 Ghz Band, 10 Channels In The 915 Mhz Band, And 1 Channel In The 868 Mhz Band Maximum Data Rates Allowed For Each Of These Frequency Bands Are Fixed As 250 Kbps @2.4 Ghz, 40 Kbps @ 915 Mhz, And 20 Kbps @868 Mhz. Allocated 16 Bit Short Or 64 Bit Extended Addresses. Allocation Of Guaranteed Time Slots (Gtss) Carrier Sense Multiple Access With Collision Avoidance (CSMA-CA) Channel Access Yields High Throughput And Low Latency For Low Duty Cycle Devices Like Sensors And Controls. Fully Hand-Shake Acknowledged Protocol For Transfer Reliability. Low Power Consumption With Battery Life Ranging From Months To Years. Energy Detection (ED). Link Quality Indication (LQI).

An FFD Can Talk To Rfds Or Other Ffds, While An RFD Can Talk Only To An FFD. An RFD Is Intended For Applications That Are Extremely Simple, Such As A Light Switch Or A Passive Infrared Sensor; They Do Not Have The Need To Send Large Amounts Of Data And May Only Associate With A Single FFD At A Time. Consequently, The RFD Can Be Implemented Using Minimal Resources And Memory Capacity.

7.4.3 Network Topologies Figure 2.1 Shows 3 Types Of Topologies That Zigbee Supports: Star Topology, Peer-To-Peer Topology And Cluster Tree.

7.4.4.Star Topology In The Star Topology, The Communication Is Established Between Devices And A Single Central Controller, Called The PAN Coordinator. The PAN Coordinator May Be Mains Powered While The Devices Will Most Likely Be Battery Powered. Applications That Benefit From This Topology Include Home Automation, Personal Computer (PC) Peripherals, Toys And Games. After An FFD Is Activated For The First Time, It May Establish Its Own Network And Become The PAN Coordinator. Each Start Network Chooses A PAN Identifier, Which Is Not Currently Used By Any Other Network Within The Radio Sphere Of Influence. This Allows Each Star Network To Operate Independently.

7.4.5.Peer-To-Peer Topology In Peer-To-Peer Topology, There Is Also One PAN Coordinator. In Contrast To Star Topology, Any Device Can Communicate With Any Other Device As Long As They Are In Range Of One Another. A Peer-To-Peer Network Can Be Ad Hoc, Self-Organizing And Self-Healing. Applications Such As Industrial Control And Monitoring, Wireless Sensor Networks, Asset And Inventory Tracking Would Benefit From Such A Topology. It Also Allows Multiple Hops

To Route Messages From Any Device To Any Other Device In The Network. It Can Provide Reliability By Multipath Routing.

Cluster Adjacent To The First One. The Advantage Of This Clustered Structure Is The Increased Coverage Area At The Cost Of Increased Message Latency Identifier (CID) Of Zero, Choosing An Unused PAN Identifier, And Broadcasting Beacon Frames To Neighboring Devices. A Candidate Device Receiving A Beacon Frame May Request To Join The Network At The CLH. If The PAN Coordinator Permits The Device To Join, It Will Add This New Device As A Child Device In Its Neighbor List. The Newly Joined Device Will Add The CLH As Its Parent In Its Neighbor List And Begin Transmitting Periodic Beacons Such That Other Candidate Devices May Then Join The Network At That Device. Once Application Or Network Requirements Are Met, The PAN Coordinator May Instruct A Device To Become The CLH Of New . 7.5.6Architecture The LR-WPAN Architecture Is Defined In Terms Of A Number Of Blocks In Order To

Simplify The Standard. These Blocks Are Called Layers. Each Layer Is Responsible For One Part Of The Standard And Offers Services To The Higher Layers. The Layout Of The Blocks Is Based On The Open Systems Interconnection (OSI) Seven-Layer Model. The Interfaces Between The Layers Serve To Define The Logical Links Between Layers. The LR-WPAN Architecture Can Be Implemented Either As Embedded Devices Or As Devices Requiring The Support Of An External Device Such As A PC. An LR-WPAN Device Comprises A PHY, Which Contains The Radio Frequency (RF) Transceiver Along With Its Low-Level Control Mechanism, And A MAC Sub Layer That Provides Access To The Physical Channel For All Types Of Transfer. 7.4.7.Network And Application Support Layer: The Network Layer Permits Growth Of Network Sans High Power Transmitters. This Layer Can Handle Huge Numbers Of Nodes. This Level In The Zigbee Architecture Includes The Zigbee Device Object (ZDO) User-Defined Application Profile(S) The Application Support (APS) Sub-Layer.

The APS Sub-Layer's Responsibilities Include Maintenance Of Tables That Enable Matching Between Two Devices And Communication Among Them, And Also Discovery, The Aspect That Identifies Other Devices That Operate In The Operating Space Of Any Device. The Responsibility Of Determining The Nature Of The Device (Coordinator / FFD Or RFD) In The Network, Commencing And Replying To Binding Requests And Ensuring A Secure Relationship Between Devices Rests With The ZDO (Zigbee Define Object). The UserDefined Application Refers To The End Device That Conforms To The Zigbee Standard. 7.4.8.Physical (PHY) Layer: The PHY Service Enables The Transmission And Reception Of PHY Protocol Data Units (PPDU) Across The Physical Radio Channel. The Features Of The IEEE 802.15.4 PHY Physical Layer Are Activation And Deactivation Of The Radio Transceiver, Energy Detection (ED), Link Quality Indication (LQI), Channel Selection, Clear Channel Assessment (CCA) And Transmitting As Well As Receiving Packets Across The Physical Medium. 7.4.9.Media Access Control (MAC) Layer: The MAC Service Enables The Transmission And Reception Of MAC Protocol Data Units (MPDU) Across The PHY Data Service. The Features Of MAC Sub Layer Are Beacon Management, Channel Access, GTS Management, Frame Validation, Acknowledged Frame Delivery, Association And Disassociation.

Figure 19:

SUPER FRAME STRUCTURE

CSMA-CA Algorithm If Superframe Structure Is Used In The PAN, Then Slotted CSMA-CA Shall Be Used. If Beacons Are Not Being Used In The PAN Or A Beacon Cannot Be Located In A Beacon-Enabled Network, Unslotted CSMA-CA Algorithm Is Used. In Both Cases, The Algorithm Is Implemented Using Units Of Time Called Backoff Periods, Which Is Equal To Aunitbackoffperiod Symbols. In Slotted CSMA-CA Channel Access Mechanism, The Backoff Period Boundaries Of Every Device In The PAN Are Aligned With The Superframe Slot Boundaries Of The PAN Coordinator. In Slotted CSMA-CA, Each Time A Device Wishes To Transmit Data Frames During The CAP, It Shall Locate The Boundary Of The Next Backoff Period. In Unslotted CSMA-CA, The Backoff Periods Of One Device Do Not Need To Be Synchronized To The Backoff Periods Of Another Device.

7.4.10.Traffic Types Zigbee/IEEE 802.15.4 Addresses Three Typical Traffic Types. IEEE 802.15.4 MAC Can Accommodate All The Types. Data Is Periodic. The Application Dictates The Rate, And The Sensor Activates Checks For Data And Deactivates. Data Is Intermittent. The Application, Or Other Stimulus, Determines The Rate, As In The Case Of Say Smoke Detectors. The Device Needs To Connect To The Network Only When Communication Is Necessitated. This Type Enables Optimum Saving On Energy. Data Is Repetitive, And The Rate Is Fixed A Priori. Depending On Allotted Time Slots, Called GTS (Guaranteed Time Slot), Devices Operate For Fixed Durations

Zigbee Employs Either Of Two Modes, Beacon Or Non-Beacon To Enable The To-And-Fro Data Traffic. Beacon Mode Is Used When The Coordinator Runs On Batteries And Thus Offers Maximum Power Savings, Whereas The Non-Beacon Mode Finds Favour When The Coordinator Is Mains-Powered. 7.4.11.Data Transfer Model Three Types Of Data Transfer Transactions Exist: From A Coordinator To A Device, From A Device To A Coordinator And Between Two Peer Devices. The Mechanism For Each Of These Transfers Depends On Whether The Network Supports The Transmission Of Beacons. The Non-Beacon Mode Will Be Included In A System Where Devices Are Asleep' Nearly Always, As In Smoke Detectors And Burglar Alarms. The Devices Wake Up And Confirm Their Continued Presence In The Network At Random Intervals.

When A Device Wishes To Transfer Data In A No Beacon-Enabled Network, It Simply Transmits Its Data Frame, Using The Unslotted CSMA-CA, To The Coordinator. On Detection

Of Activity, The Sensors Spring To Attention', As It Were, And Transmit To The Ever-Waiting Coordinator's Receiver (Since It Is Mains-Powered). There Is Also An Optional Acknowledgement At The End As Shown In Figure 4.3.

In The Beacon Mode, A Device Watches Out For The Coordinator's Beacon That Gets Transmitted At Periodically, Locks On And Looks For Messages Addressed To It. If Message Transmission Is Complete, The Coordinator Dictates A Schedule For The Next Beacon So That The Device Goes To Sleep'; In Fact, The Coordinator Itself Switches To Sleep Mode. While Using The Beacon Mode, All The Devices In A Mesh Network Know When To Communicate With Each Other. In This Mode, Necessarily, The Timing Circuits Have To Be Quite Accurate, Or Wake Up Sooner To Be Sure Not To Miss The Beacon. This In Turn Means An Increase In Power Consumption By The Coordinator's Receiver, Entailing An Optimal Increase In Costs.

Fig20: When A Device Wishes To Transfer Data To A Coordinator In A Beacon-Enabled Network, It First Listens For The Network Beacon. When The Beacon Is Found, It Synchronizes To The Superframe Structure. At The Right Time, It Transmits Its Data Frame, Using Slotted CSMACA, To The Coordinator. There Is An Optional Acknowledgement At The End As Shown In .

The Applications Transfers Are Completely Controlled By The Devices On A PAN Rather Than By The Coordinator. This Provides The Energy-Conservation Feature Of The Zigbee Network. When A Coordinator Wishes To Transfer Data To A Device In A Beacon-Enabled Network, It Indicates In The Network Beacon That The Data Message Is Pending. The Device Periodically Listens To The Network Beacon, And If A Message Is Pending, Transmits A MAC Command Requesting This Data, Using Slotted CSMA-CA . The Coordinator Optionally Acknowledges The Successful Transmission Of This Packet. The Pending Data Frame Is Then Sent Using Transmitting An Acknowledgement Frame. Upon Receiving The Acknowledgement, The Message Is Removed From The List Of Pending Messages In The Beacon As Shown In Figure

. Slotted CSMA-CA. The Device Acknowledged The Successful Reception Of The Data By

When A Coordinator Wishes To Transfer Data To A Device In A Nonbeacon-Enabled Network, It Stores The Data For The Appropriate Device To Make Contact And Request Data. A Device May Make Contact By Transmitting A MAC Command Requesting The Data, Using Unslotted CSMA-CA, To Its Coordinator At An Application-Defined Rate. The Coordinator Acknowledges This Packet. If Data Are Pending, The Coordinator Transmits The Data Frame Using Unslotted CSMA-CA. If Data Are Not Pending, The Coordinator Transmits A Data Frame With A Zero-Length Payload To Indicate That No Data Were Pending. The Device Acknowledges This Packet As Shown In Figure 4.6.

In A Peer-To-Peer Network, Every Device Can Communicate With Any Other Device In Its Transmission Radius. There Are Two Options For This. In The First Case, The Node Will Listen Constantly And Transmit Its Data Using Unslotted CSMA-CA. In The Second Case, The Nodes Synchronize With Each Other So That They Can Save Power. 7.4. ZIGBEE ROUTING LAYER

AODV: Ad Hoc On Demand Distance Vector AODV Is A Pure On-Demand Route Acquisition Algorithm: Nodes That Do Not Lie On Active Paths Neither Maintain Any Routing Information Nor Participate In Any Periodic Routing Table Exchanges. Further, A Node Does Not Have To Discover And Maintain A Route To Another Node Until The Two Needs To Communicate, Unless The Former Node Is Offering Services As An Intermediate Forwarding Station To Maintain Connectivity Between Two Other Nodes.

The Primary Objectives Of The Algorithm Are To Broadcast Discovery Packets Only When Necessary, To Distinguish Between Local Connectivity Management And General Topology Maintenance And To Disseminate Information About Changes In Local Connectivity To Those Neighboring Mobile Nodes That Are Likely To Need The Information. When A Source Node Needs To Communicate With Another Node For Which It Has No Routing Information In Its Table, The Path Discovery Process Is Initiated. Every Node Maintains Two Separate Counters: Sequence Number And Broadcast Id. The Source Node Initiates Path Discovery By Broadcasting A Route Request (RREQ) Packet To Its Neighbors, Which Includes Source Addr, Source Sequence Number, Broadcast Id, Dest Addr, Dest Sequence Number, Hop Cnt. (Source Sequence Number Is For Maintaining Freshness Information About The Reverse Route Whereas The Destination Sequence Number Is For Maintaining Freshness Of The Route To The Destination Before It Can Be Accepted By The Source.). The Pair Source Addr, Broadcast Id Uniquely Identifies A RREQ, Where Broadcast Id Is Incremented Whenever The Source Issues A New RREQ.When An Intermediate Node Receives A RREQ, If It Has Already Received A RREQ With The Same Broadcast Id And Source Address, It Drops The Redundant RREQ And Does Not Rebroadcast It. Otherwise, It Rebroadcasts It To Its Own Neighbors After Increasing Hop Cnt. Each Node Keeps The

Following Information: Destination IP Address, Source IP Address, Broadcast Id, Expiration Time For Reverse Path Route Entry And Source Nodes Sequence Number. As The RREQ Travels From A Source To Destinations, It Automatically Sets Up The Reverse Path From All Nodes Back To The Source. To Set Up A Reverse Path, A Node Records The Address Of The Neighbor From Which It Received The First Copy Of RREQ. These Reverse Path Route Entries Are Maintained For At Least Enough Time For The RREQ To Traverse The Network And Produce A Reply To The Sender. When The RREQ Arrives At A Node, Possibly The Destination Itself, That Possesses A Current Route To The Destination, The Receiving Node First Checks That The RREQ Was Received Over A Bi-Directional Link. If This Node Is Not Destination But Has Route To The Destination, It Determines Whether The Route Is Current By Comparing The Destination Sequence Number In Its Own Route Entry To The Destination Sequence Number In The RREQ. If RREQs Sequence Number For The Destination Is Greater Than That Recorded By The Intermediate Node, The Intermediate Node Must Not Use This Route To Respond To The RREQ, Instead Rebroadcasts The RREQ. If The Route Has A Destination Sequence Number That Is Greater Than That Contained In The RREQ Or Equal To That Contained In The RREQ But A Smaller Hop Count, It Can Uncast A Route Reply Packet (RREP) Back To Its Neighbor From Which It Received The RREQ. A RREP Contains The Following Information: Source Addr, Dest Addr, Dest Sequence Number, Hop Cnt And Lifetime. As The RREP Travels Back To The Source, Each Node Along The Path Sets Up A Forward Pointer To The Node From Which The RREP Came, Updates Its Timeout Information For Route Entries To The Source And Destination, And Records The Latest Destination Sequence Number For The Requested Destination. Nodes That Are Along The Path Determined By The RREP Will Timeout After Route Request Expiration Timer And Will Delete The Reverse Pointers Since They Are Not On The Path From Source To Destination As Shown In Figure 5.1. The Value Of This Timeout Time Depends On The Size Of The Ad Hoc Network.

SOFTWARE Components A) ABOUT SOFTWARE Software used is: *Keil software for C programming *Express PCB for lay out design *Express SCH for schematic design KEIL Vision3 What's New in Vision3? Vision3 adds many new features to the Editor like Text Templates, Quick Function Navigation, and Syntax Coloring with brace high lighting Configuration Wizard for dialog based startup and debugger setup. Vision3 is fully compatible to Vision2 and can be used in parallel with Vision2. What is Vision3? Vision3 is an IDE (Integrated Development Environment) that helps you write, compile, and debug embedded programs. It encapsulates the following components: A project manager. A make facility. Tool configuration. Editor. A powerful debugger.

Express PCB Express PCB is a Circuit Design Software and PCB manufacturing service. One can learn almost everything you need to know about Express PCB from the help topics included with the programs given. Details: Express PCB, Version 5.6.0 Express SCH The Express SCH schematic design program is very easy to use. This software enables the user to draw the Schematics with drag and drop options. A Quick Start Guide is provided by which the user can learn how to use it. 81

Details: Express SCH, Version 5.6.0

EMBEDDED C: The programming Language used here in this project is an Embedded C Language. This Embedded C Language is different from the generic C language in few things like a) Data types b) Access over the architecture addresses. The Embedded C Programming Language forms the user friendly language with access over Port addresses, SFR Register addresses etc. Embedded C Data types: Data Types unsigned char signed char unsigned int signed int sbit bit sfr Size in Bits 8-bit 8-bit 16-bit 16-bit 1-bit 1-bit 8-bit Data Range/Usage 0-255 -128 to +127 0 to 65535 -32,768 to +32,767 SFR bit addressable only RAM bit addressable only RAM addresses 80-FFH only Signed char: o Used to represent the or + values. o As a result, we have only 7 bits for the magnitude of the signed number, giving us values from -128 to +127.

82

B) Vision3 Vision3 is an IDE (Integrated Development Environment) that helps you write, compile, and debug embedded programs. It encapsulates the following components: A project manager. A make facility. Tool configuration. Editor. A powerful debugger.

To help you get started, several example programs (located in the \C51\Examples, \C251\Examples, \C166\Examples, and \ARM\...\Examples) are provided. HELLO is a simple program that prints the string "Hello World" using the Serial Interface. Building an Application in Vision2 To build (compile, assemble, and link) an application in Vision2, you must: 1. Select Project - (for example, 166\EXAMPLES\HELLO\HELLO.UV2). 2. Select Project - Rebuild all target files or Build target. Vision2 compiles, assembles, and links the files in your project.

Creating Your Own Application in Vision2 To create a new project in Vision2, you must: 1. Select Project - New Project. 2. Select a directory and enter the name of the project file. 3. Select Project - Select Device and select an 8051, 251, or C16x/ST10 device from the Device Database. 4. Create source files to add to the project. 5. Select Project - Targets, Groups, Files, Add/Files, select Source Group1, and add the source files to the project. 6. Select Project - Options and set the tool options. Note when you select the target device from the Device Database all special options are set automatically. You typically only need to configure the memory map of your target hardware. Default memory model settings are optimal for most applications. 7. Select Project - Rebuild all target files or Build target. Debugging an Application in Vision2 To debug an application created using Vision2, you must: 83

1. Select Debug - Start/Stop Debug Session. 2. Use the Step toolbar buttons to single-step through your program. You may enter G, main in the Output Window to execute to the main C function. 3. Open the Serial Window using the Serial #1 button on the toolbar. Debug your program using standard options like Step, Go, Break, and so on. Starting Vision2 and creating a Project Vision2 is a standard Windows application and started by clicking on the program icon. To create a new project file select from the Vision2 menu Project New Project. This opens a standard Windows dialog that asks you for the new project file name. We suggest that you use a separate folder for each project. You can simply use the icon Create New Folder in this dialog to get a new empty folder. Then select this folder and enter the file name for the new project, i.e. Project1. Vision2 creates a new project file with the name PROJECT1.UV2 which contains a default target and file group name. You can see these names in the Project Window Files. Now use from the menu Project Select Device for Target and select a CPU for your project. The Select Device dialog box shows the Vision2 device database. Just select the microcontroller you use. We are using for our examples the Philips 80C51RD+ CPU. This selection sets necessary tool options for the 80C51RD+ device and simplifies in this way the tool Configuration Building Projects and Creating a HEX Files Typical, the tool settings under Options Target are all you need to start a new application. You may translate all source files and line the application with a click on the Build Target toolbar icon. When you build an application with syntax errors, Vision2 will display errors and warning messages in the Output Window Build page. A double click on a message line opens the source file on the correct location in a Vision2 editor window. Once you have successfully generated your application you can start debugging. After you have tested your application, it is required to create an Intel HEX file to download the software into an EPROM programmer or simulator. Vision2 creates HEX files with each build process when Create HEX files under Options for Target Output is enabled. You may start your PROM programming utility after the make process when you specify the program under the option Run User Program #1.

CPU Simulation 84

Vision2 simulates up to 16 Mbytes of memory from which areas can be mapped for read, write, or code execution access. The Vision2 simulator traps and reports illegal memory accesses being done. In addition to memory mapping, the simulator also provides support for the integrated peripherals of the various 8051 derivatives. The on-chip peripherals of the CPU you have selected are configured from the Device Database selection You have made when you create your project target. Refer to page 58 for more Information about selecting a device. You may select and display the on-chip peripheral components using the Debug menu. You can also change the aspects of each peripheral using the controls in the dialog boxes. Start Debugging You start the debug mode of Vision2 with the Debug Start/Stop Debug Session command. Depending on the Options for Target Debug Configuration, Vision2 will load the application program and run the startup code Vision2 saves the editor screen layout and restores the screen layout of the last debug session. If the program execution stops, Vision2 opens an editor window with the source text or shows CPU instructions in the disassembly window. The next executable statement is marked with a yellow arrow. During debugging, most editor features are still available. For example, you can use the find command or correct program errors. Program source text of your application is shown in the same windows. The Vision2 debug mode differs from the edit mode in the following aspects: _ The Debug Menu and Debug Commands described on page 28 are Available. The additional debug windows are discussed in the following. _ The project structure or tool parameters cannot be modified. All build Commands are disabled. Disassembly Window The Disassembly window shows your target program as mixed source and assembly program or just assembly code. A trace history of previously executed instructions may be displayed with Debug View Trace Records. To enable the trace history, set Debug Enable/Disable Trace Recording. If you select the Disassembly Window as the active window all program step commands work on CPU instruction level rather than program source lines. You can select a text line and set or modify code breakpoints using toolbar buttons or the context menu commands. You may use the dialog Debug Inline Assembly to modify the CPU instructions. That allows you to correct mistakes or to make temporary changes to the target program you are debugging. SOURCE CODE

1.

Click on the Keil uVision Icon on Desktop 85

2.

The following fig will appear

3. 4.

Click on the Project menu from the title bar Then Click on New Project

5.

Save the Project by typing suitable project name with no extension in u r own folder sited in either C:\ or D:\

86

6. 7. 8.

Then Click on save button above. Select the component for u r project. i.e. Atmel Click on the + Symbol beside of Atmel

9.

Select AT89C51 as shown below

87

10. 11.

Then Click on OK The Following fig will appear

12.

Then Click either YES or NOmostly NO

13. 14.

Now your project is ready to USE Now double click on the Target1, you would get another option Source group 1 as shown in next page. 88

15.

Click on the file option from menu bar and select new

16.

The next screen will be as shown in next page, and just maximize it by double clicking on its blue boarder.

89

17. 18.

Now start writing program in either in C or ASM For a program written in Assembly, then save it with extension . asm and for C based program save it with extension .C

19.

Now right click on Source group 1 and click on Add files to Group Source

90

20.

Now you will get another window, on which by default C files will appear.

21. 22. 23.

Now select as per your file extension given while saving the file Click only one time on option ADD Now Press function key F7 to compile. Any error will appear if so happen.

91

24. 25.

If the file contains no error, then press Control+F5 simultaneously. The new window is as follows

26.

Then Click OK

27.

Now Click on the Peripherals from menu bar, and check your required port as shown in fig below

92

28.

Drag the port a side and click in the program file.

29. 30.

Now keep Pressing function key F11 slowly and observe. You are running your program successfully

CONCLUSION

FUTURE ASPECTS

93

BIBLIOGRAPHY NAME OF THE SITES

1. 2. 3. 4.

WWW.MITEL.DATABOOK.COM WWW.ATMEL.DATABOOK.COM WWW.FRANKLIN.COM WWW.KEIL.COM

REFERENCES 1. 8051-MICROCONTROLLER AND EMBEDDED SYSTEM. Mohd. Mazidi.

94

Vous aimerez peut-être aussi