You are on page 1of 135


INDEX CONTENTS Abbreviations 1. Figure Locations 2. Introduction to the project 3. Block Diagra m 4. Block Diagram Description 5. Schematic 6. Schematic Description 7. Introduc tion to GSM and GPS technology 8. Hardware Components Micro controllers ZIGBEE T RANSCEIVER MAX 232 H-BRIDGE(L293D) DC GEARED MOTOR CAMERA LANDMINE SENSOR Power Supply PC 9. Circuit Description 10. Software components a. About Keil b. Embedd ed C 11. Source Code 12. Conclusion (or) Synopsis 13. Future Aspects 14.Bibliograp hy 1

1.Abbreviations: Microcontroller: Symbol ACC B PSW SP DPTR DPL DPH P0 P1 P2 P3 IP IE TMOD TCON T2CON T2MOD TH0 TL0 TH1 TL 1 TH2 TL2 SCON SBUF PCON Name Accumulator B register Program status word Stack pointer Data pointer 2 bytes Lo w byte High byte Port0 Port1 Port2 Port3 Interrupt priority control Interrupt en able control Timer/counter mode control Timer/counter control Timer/counter 2 co ntrol Timer/counter mode2 control Timer/counter 0high byte Timer/counter 0 low b yte 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 Power control ZIGBEE: IEEE WPAN AES FFD RFD LOS rical engineers Wireless Personal function device Reduced function cess/collision avoidance Clear to 2 CSMA/CA CTS Institute of electronics and elect Area Network Advanced encryption standard Full device Line of sight Carrier sense multiple ac send

RTS DIN DOUT UART BD CE DH-DL SH-SL MY ND NI DN AC PHY MAC APL NWK ZDO AF CCA Request to send Data in Data out Universal asynchronous receiver and transmitter Baud rate Coordinator enable Destination high-destination low Serial high-seria l low 16-bit source address(my address) Node discover Node identifier Destinatio n node Apply changes Physical layer Media access control Application layer Netwo rk layer Zigbee device object Application frame Clear channel assessment 2.Figure Locations: 1. Block diagram 2. Schematics 3. Network topologies 4. Various wireless technol ogies 5. Architecture of AT89C51 6. Pin description of AT89C51 7. External clock drive configuration 8. Program memory 9. Data memory 10. 89C51 memory structure 11. PSW register 12. DB9 connector 13. Connection diagram of MAX232 14. Transmi tter flow chat 15. Receiver flow chat 16. Pin diagram of MAX232 17. Female conne ctor 18. Male connector 19. Block Diagram of the DC motor 20. Block Diagram of t he DC motor having two poles only 21. Block Diagram of the DC motor having Three poles 22. Internal Block Diagram of the Three pole DC motor 23. H-bridge 3

24. Zigbee Transceiver 25. Data flow diagram 26. Serial data sequence 27. Intern al data flow diagram 28. NonBeacon Peer-to-Peer Architecture 29. Different Modes of Operation 30. Syntax for sending AT Commands 31. Zigbee Architecture 32. LM 7805 regulator IC 33. Block diagram of power supply 34. Circuit diagram of power supply 35. Typical bridge rectifier 36. Current flow in bridge rectifier 3.INTRODUCTION TO EMBEDDED SYSTEMS: Embedded systems are designed to do some specific task rather than be a generalp urpose computer for multiple tasks.Some also has real time performance constrain ts that must be met, for reason such as safety and usability; others may have lo w or no performance requirements, allowing the system hardware to be simplified to reduce costs. An embedded system is not always a separate block - very often it is physically builtin to the device it is controlling. The software written f or embedded systems is often called firmware, and is stored in read-only memory or flash convector chips rather than a disk drive. It often runs with limited co mputer hardware resources: small or no keyboard, screen, and little memory. Communication: Communication refers to the sending, receiving and processing of information by electric means. As such, it started with wire telegraphy in the early 80s, develo ping with telephony and radio some decades later. Radio communication became the most widely used and refined through the invention of and use of transistor, in tegrated circuit, and other semiconductor devices. Most recently, the use of sat ellites and fiber optics has made 4

communication even more wide spread, with an increasing emphasis on computer and other data communications. A modern communications system is first concerned wi th the sorting, processing and storing of information before its transmission. T he actual transmission then follows, with further processing and the filtering o f noise. Finally we have reception, which may include processing steps such as d ecoding, storage and interpretation. In this context, forms of communications in clude radio, telephony and telegraphy, broadcast, point to point and mobile comm unications (commercial and military), computer communications, radar, radio tele metry and radio aids to navigation. It is also important to consider the human f actors influencing a particular system, since they can always affect its design, planning and use. In this project PC controlled military robot using zigbee, like the title indicates the controlling action of Robot is done through the PC. The robot is kept some other place and we can operate the robot by sitting in front of the PC through the 2.4 GHz RF communication i.e. Zigbee. ZIGBEE is a new wir eless technology guided by the IEEE 802.15.4 Personal Area Networks standard. It is primarily designed for the wide ranging automation applications and to repla ce the existing non-standard technologies. It currently operates in the 868MHz b and at a data rate of 20Kbps in Europe, 914MHz band at 40Kbps in the USA, and th e 2.4GHz ISM bands Worldwide at a maximum data-rate of 250Kbps. The ZIGBEE speci fication is a combination of Home RF Lite and the 802.15.4 specification. The sp ecification operates in the 2.4GHz (ISM) radio band the same band as 802.11b, Bl uetooth microwaves and some other devices. It is capable of connecting 255 devic es per network. The specification supports data transmission rates of up to 250 Kbps at a range of up to 30 meters. ZIGBEE s technology is slower than 802.11b ( 11 Mbps) and Bluetooth (1 Mbps) but it consumes significantly less power. INTRODUCTION TO PROJECT Now a day s every system is automated in order to face new challenges. In the pr esent days Automated systems have less manual operations, flexibility, reliabili ty and accurate. Due to this demand every field prefers automated control system s. Especially in the field of electronics automated systems are giving good perf ormance. and we can implement a system in which a robot direction can be control led wirelessly with respect to the commands given by the user through PC using Z igbee technology. 5

In this project pc controlled military robot using Zigbee, like the title indicate s that controlling action of Robot is done through PC and a new wireless technol ogy called Zigbee. This project is to design a robotic system for military applica tions using zigbee technology. Here in this project robot is controlled through PC. Zigbee is a new wireless technology guided by IEEE 802.15.4 Personal Area Ne twork standard. And can communicate with 2.4GHZ In transmitter, the microcontrol ler will route the notice to receiver using Zigbee transceiver and in receiver s ide the received notice is going to display in LCD. 4.BLOCK DIAGRAM: TRANSMITTER SECTION: LCD PC MAX232 ZIGBEE TRANSCEIVER MICRO CONTROLLER POWER SUPPLY 6


H-BRIDGE ZIGBEE TRANSCEIVER MOTOR MICRO CONTROLLER MOTOR DRIVER POWER SUPPLY 5.BLOCK DIAGRAM EXPLANATION: This Project mainly consists of Power Supply section, Microcontroller section, Z igbee transreceiver, H-bridge, dc motor ,PC and Max-232. Micro controller: In this project work the micro-controller is plays major role. Microcontrollers were originally used as components in complicated process-control systems. Howev er, because of their small size and low price, Micro-controllers are now also be ing used in regulators for individual control loops. In several areas Microcontr ollers are now outperforming their analog counterparts and are cheaper as well. MAX- 232 8

To allow compatibility among data communication equipment made by various manufa ctures, an interfacing standard called RS232 was set by the Electronic Industrie s Association (EIA). This RS-232 standard is used in PCs and numerous types of e quipment .However, since the standard was set long before the advent of the TTL logic family, its input and output voltage levels are not TTL compatible. In RS232 ,a 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 RS-232 to a microcontroller system we must use voltage converters such as MAX232 to convert the TTL logic levels to the RS-232 voltage levels and vice versa. So here we are using this MAX-232 to have compatibility between the GSM MODEM and microcontroller. ZIGBEE: Zigbee is new wireless technology guided by IEEE 802.15.4 Personal Area Network standard. It is primarily designed for the wide ranging controlling applications and to re place the existing non-standard technologies. It currently operates in 868MHz ba nd at a data rate of 20Kbps in Europe, 914MHz band at 40kbps in USA, and the 2.4 GHz ISM bands Worldwide at a maximum data-rate of 250kbps POWER SUPPLY This section is meant for supplying Power to all the sections mentioned above. I t basically consists of a Transformer to step down the 230V ac to 18V ac followe d by diodes. Here diodes are used to rectify the ac to dc. After rectification t he obtained rippled dc is filtered using a capacitor Filter. A positive voltage regulator is used to regulate the obtained dc voltage. But here in this project two power supplies are used one is meant to supply operating voltage for Microco ntroller and the other is to supply control voltage for Relays. H-BRIDGE: H-bridge. Sometimes called a "full bridge" the H-bridge is so named because it h as four switching elements at the "corners" of the H and the motor forms the cro ss bar. The key fact to note is that there are, in theory, four switching elemen ts within the bridge. These four elements are often called, high side left, high side right, low side right, and low side left (when traversing in clockwise ord er). 9

DC Motor DC motors are configured in many types and sizes, including brush less, servo, a nd gear motor types. A motor consists of a rotor and a permanent magnetic field stator. The magnetic field is maintained using either permanent magnets or elect romagnetic windings. DC motors are most commonly used in variable speed and torq ue. 6.SCHEMATIC DIAGRAM: TRANSMITTER: RECEIVER: 10

7.SCHEMATIC EXPLANATION: Transmitter: 1. Latch (74LS244) Data pins: Pins (9, 16) - P3.0 Pins (2, 13) - P3.1 Pin 4 - MA X 12 pin Pin 18 - MAX 11 pin Pin 11 - Zigbee 2 pin Pin 12 - ZigBee 3 pin Pin 20 VCC Pin 10 - GND Control pins: Pin 1- P3.6 Pin 19 - P3.7 2. MAX232: Data pins: P in 14-DB9 connector 2 pin (to PC) 11

Pin 13-DB9 connector 3 pin (to PC) 3. Microcontroller: Pin 40- VCC Pin 20 GND Pin 18-XTAL1 Pin 19-XTAL2 Receiver: 1. ZigBee connection Xbee 2-P3.0 Xbee 3-P3.1 2. Microcontroller: Pin 40- VCC Pin 20 GND Pin 18-XTAL1 Pin 19-XTAL2 3. H-bridge: H-bridge connections (4 pins) P1.0P1.3 Power supply: In this system we are using 5V power supply for microcontroller at pin 40 of Tra nsmitter section as well as receiver section. Where as for ZigBee transceiver we are providing a voltage of 3V to pin 1 all transceivers .The full description o f the Power supply section is given in this documentation in the following secti ons i.e. hardware components. Latch: In this section all the pin connections clearly. Zigbee transceiver is used for atch i.e. the DOUT (pin 2 of Zigbee) is and DIN (pin 3 of Zigbee) is connected nd pin 10 are used for VCC and GND. PC: 12 of IC s and other devices are explained transmitting data. So it get data from l connected to the pin 11 of latch 74LS244 to the pin 12 of latch 74LS244. Pin 20 a

Here Latch pins 18 and 4 are connected to MAX 232 pins 11 and 12 respectively. F rom MAX 14 and 13 pins it is connected to 2 and 3 pins of DB9 connector respecti vely to get data from PC. Microcontroller: The RxD (pin 10) and TxD (pin 11) pins of microcontroller are connected to latch through to (9, 16) and (2, 3) respectively. Receiver: Zigbee transceiver: Here Zigbee transceiver is used for receiving data from transmitter. To transfer data between microcontroller and ZigBee we use two pins, one is transmission (T xD) and reception (RxD). The DOUT (pin 2 of Zigbee) is connected to the pin P3.0 and DIN (pin 3 of Zigbee) is connected to P3.0. Power supply: In this system we are using 5V power supply for microcontroller at pin 40 of Tra nsmitter section as well as receiver section. Where as for ZigBee transceiver we are proving a voltage of 3V to pin 1 all transceivers .The full description of the Power supply section is given in this documentation in the following section s i.e. hardware components. H-Bridge Connections to Micro controller: We are usi ng two H-bridges to control robot .One H-bridge inputs are connected to the 1st and 2nd pins of the Micro controller. The other H-bridge inputs are connected to the 3rd and 4th pins of the Micro controller. ZIGBEE Technology: ZIGBEE is a new wireless technology guided by the IEEE 802.15.4 Personal Area Ne tworks standard. It is primarily designed for the wide ranging automation applic ations and to replace the existing non-standard technologies. It currently opera tes in the 868MHz band at a data rate of 20Kbps in Europe, 914MHz band at 40Kbps in the USA, and the 2.4GHz ISM bands Worldwide at a maximum data-rate of 250Kbp s. 13

The ZIGBEE specification is a combination of HomeRF Lite and the 802.15.4 specif ication. The specification operates in the 2.4GHz (ISM) radio band - the same ba nd as 802.11b standard, Bluetooth, microwaves and some other devices. It is capa ble of connecting 255 devices per network. The specification supports data trans mission rates of up to 250 Kbps at a range of up to 30 meters. ZIGBEE s technolo gy is slower than 802.11b (11 Mbps) and Bluetooth (1 Mbps) but it consumes signi ficantly less power. 802.15.4 (ZIGBEE) is a new standard uniquely designed for l ow rate wireless personal area networks. It targets low data rate, low power con sumption and low cost wireless networking, and its goal is to provide a physical -layer and MAC-layer standard for such networks. Wireless networks provide advan tages in deployment, cost, size and distributed intelligence when compared with wired networks. This technology allows users to set up a network quickly, and al lows them to set up networks where it is impossible or inconvenient to wire cabl es. Wireless networks are more cost-efficient than wired networks in general. Bl uetooth (802.15.1) was the first well-known wireless standard facing low data ra te applications. The effort of Bluetooth to cover more applications and provide quality of service has led to its deviation from the design goal of simplicity, which makes it expensive and inappropriate for some simple applications requirin g low cost and low power consumption. These are the kind of applications this ne w standard is focused on. It s relevant to compare here Bluetooth and ZIGBEE, as they are sometimes seen as competitors, to show their differences and to clarif y for which applications suits each of them. The data transfer capabilities are much higher in Bluetooth, which is capable of transmitting audio, graphics and p ictures over small networks, and also appropriate for file transfers. ZIGBEE, on the other hand, is better suited for transmitting smaller packets over large ne tworks; mostly static networks with many, infrequently used devices, like home a utomation, toys, remote controls, etc. While the performance of a Bluetooth netw ork drops when more than 8 devices are present, ZIGBEE networks can handle 65000 + devices. Probably the main feature of ZIGBEE is its limited power requirement. ZIGBEE is better for devices where the battery is rarely replaced, as it is des igned to optimize slave power requirements, and battery life can be up to 2 year s with normal batteries. Bluetooth is a 14

cable replacement for items like phones, laptop computers and headsets. Bluetoot h devices expect regular charging and use a power model like a mobile phone. ZIG BEE is also outstanding when facing timing critical, low power applications. The join time for a new slave is typically 30ms, and the time needed by a slave cha nging from sleeping to active, or accessing the channel is typically 15ms. Bluet ooth devices need 3 seconds to either join a network or to change to active from sleeping state, though they are much faster accessing the channel (around 2ms). Need for ZIGBEE Technology: ZIGBEE is the only wireless standards-based technology that addresses the unique needs of remote monitoring and control, sensory network applications. Sensors a nd controls dont need high bandwidth but they do need low latency and very low en ergy consumption for long battery lives and for large device arrays. There are a multitude of standards that address mid to high data rates for voice, PC LANs, video, etc. However, up till now there hasnt been a wireless network standard tha t meets the unique needs of sensors and control devices. There are a multitude o f proprietary wireless systems manufactured today to solve a multitude of proble ms that also dont require high data rates but do require low cost and very low cu rrent drain. This network has large number of nodes when compared to other techn ologies. It is easy to deploy and configure i.e., if any new node enters into th e network it automatically senses and configure it. The Zigbee device is interop erable. 2.3 Features Standards-based wireless technology Interoperability and worldwide usability Low data-rates Ultra low power consumption Very small protocol stack Support for sm all to excessively large networks Simple design Security Reliability 2.4 Parameters 15

Operating frequency

Operating voltage

Transmitted power


Data rate

: 2.4GHz : 3.3V : 1mw : 30m(urban area), 200m (LOS) : 250Kbps : -104dbm : 2.4 2. 4875 GHz. Operating temperature range : -40oC to +80oC e 2.5 Network Topologies Fig 2.1 Network Topologies There are three different network topologies that are supported by Zigbee, namely the star, mesh and cluster tree or hybrid networks. Each has its own advantages and can be used to advantage in different situation s. The star network is commonly used, having the advantage of simplicity. In the star topology, the communication is established between devices and a single ce ntral controller, called the PAN coordinator. The PAN coordinator is the primary controller of the PAN. All 16 Receiver sensitivity Frequency rang

devices operating on a network of either topology shall have unique 64 bit exten ded address, which can be exchanged for a short address allocated by the PAN coo rdinator when the device associates. Mesh or peer-to-peer networks enable high d egrees of reliability. The mesh topology also has a PAN coordinator, but any dev ice can communicate with any other device as long as they are in range of one an other. Mesh topology allows more complex network formations to be implemented. M esh networking allows for redundancy in node links, so that if one node goes dow n, devices can find an alternative path to communicate with one another. Cluster Tree network is essentially a combination of star and mesh topologies. Each ind ependent PAN will select a unique identifier. This PAN identifier allows communi cations between devices within a network using short addresses and enables trans missions between devices across independent networks. Network Elements There are three network elements: PAN Coordinator (Personal Area Network Coordin ator) The central coordinator in a network is called PAN Coordinator. The PAN Co ordinator is the primary controller of the PAN. Uses a specific 16-bit PAN ID. I t has self healing property. FFD (Full Function Device) This acts as a ZigBee Ro uter. Helps form the mesh and route data. This performs other functions like sen sing. RFD (Reduced Function Device) This cannot act as a router. This is the end node of the network. One RFD node cannot communicate directly with other RFD node. 17

2.6 Wireless technologies Fig 2.2 Various Wireless Technologies The above figure illustrates data rates an d operating range of Zigbee in comparison with other wireless technologies. The different technologies and standards mentioned above are classified under two ne tworks. WPAN (Wireless Personal Area Network) WLAN (Wireless local Area Network) In WPAN we have two competing technologies Zigbee, Bluetooth. The data rate of Zigbee is 250 kbps and that of Bluetooth is 1Mbps. Zigbee is focused on automati on whereas Bluetooth focuses on connectivity between laptops and PDAs. In WLAN we have other technologies like WI-FI, WIMAX and HiperLAN. The data rates are high in WLAN which ranges from 1-54 Mbps. These technologies are costlier and comple x when compared Zigbee. The below table shows the difference between different w ireless technologies. Table: 2.1 Comparisons of Various WLAN Technologies ZigBee 802.11 Bluetooth UWB (Ultra Wireless (Wi-Fi) Wide Band) USB IR Wireless 18

Data Rate 20, 40, and 250 Kbits/s 10-100 meters 11 & 54 Mbits/sec 50-100 meters 1 Mbits/s 100-500 Mbits/s <10 meters 62.5 Kbits/s 20-40 Kbits/s <10 meters (LOS) Range 10 meters 10 meters Networking peer to peer, Point to hub Ad-hoc, very Point to point Point to point Point to Topology star, or mesh small point networks Operating Frequency Comple xity Power Consumption Security 2.4 GHz 2.4 & 5 GHz 2.4 GHz 3.1-10.6 GHz 2.4 GHz 800-900 nm Low Low Low Very low 128 AES plus application layer security High High High Medium 64 and 128 bit encryption Medium Low Low Low Typical Applications Industrial Wireless LAN Wireless Streaming PC peripheral Remote control and conn ectivity, connectivity video, home connections controls, monitoring, broadband b etween entertainment PC, PDA, sensor Internet access devices such applications p hone, networks, as phones, laptop links building PDA, laptops, automation, heads ets home control Application: Building Automation Asset Tracking 19 HVAC Control

Building Lighting

Industrial Control Asset Management Process Control Energy Management Metering Medical Sensing and Monitoring

Environmental Monitor

Patient monitoring Fitness monitoring Consumer Electronics o TV o VCR o DVD/CD o Remote Control o Interactive Toys BUILDING PC and Peripherals Mouse Keyboard Joystick Commercial control Home Security Lawn Irrigation Home Remote Control Home Remote monitor

8.HARDWARE DESIGN: Introduction 20

IN this chapter we are going to cover all parts of wireless data transfer between two or more PCs in detailed manner and their functions in brief. Here we are more interested about the Microcontroller since it is the heart of the project. So t he complete architecture is explained and also significance of the Microcontroll er. Hardware components: 1. microcontroller 2. transceiver 3. power supply 4. DC motor 5. H-bridge MICROCONTROLLER Introduction: A Micro controller consists of a powerful CPU tigh tly coupled with memory RAM, ROM or EPROM), various I / O features such as Seria l ports, Parallel Ports, Timer/Counters, Interrupt Controller, Data Acquisition interfaces-Analog to Digital Converter (ADC), Digital to Analog Converter (ADC), everything integrated onto a single Silicon Chip. It does not mean that any mic ro controller should have all the above said features on chip, Depending on the need and area of application for which it is designed, The ON-CHIP features pres ent in it may or may not include all the individual section said above. Any micr ocomputer system requires memory to store a sequence of instructions making up a program, parallel port or serial port for communicating with an external system , timer / counter for control purposes like generating time delays, Baud rate fo r the serial port, apart from the controlling unit called the Central Processing Unit. Advantages of microcontrollers: A system is developed with a microprocess or, the designer has to go for external memory such as RAM, ROM or EPROM and per ipherals and hence the size of the PCB will be large enough to hold all the requ ired peripherals. But, the micro controller has got all these peripheral facilit ies on a single chip so development of a similar system with a micro controller reduces PCB size and cost of the design. One of the major differences between a micro controller and a microprocessor is that a controller often deals with bits , not bytes as in the real world application, for example switch 21

contacts can only be open or close, indicators should be lit or dark and motors can be either turned on or off and so forth.

INTRODUCTION TO ATMEL MICROCONTROLLER SERIES: 89C51 Family, TECHNOLOGY: CMOS The major Features of 8-bit Micro control ler ATMEL 89C51: 8 Bit CPU optimized for control applications Exten processing (Single - bit Logic) Capabilities. On - Chip Flash Program Memory On - Chip Data RAM Bi-directional and Individually Addressable I/O Lines Multiple 1 6-Bit Timer/Counters Full Duplex UART Multiple Source / Vector / Priority Interr upt Structure On - Chip Oscillator and Clock circuitry. On - Chip EEPROM SPI Ser ial Bus Interface Watch Dog Timer 8051 BLOCK DIAGRAM: 22

Fig. 6.2.1 Architecture of AT89C51 PIN CONFIGURATION: 23

Pin Diagram of AT89C51 Pin Description: VCC GND Port 0 24 Supply voltage. Ground.

Port 0 is an 8-bit open drain bidirectional I/O port. As an output port each pin can sink eight TTL inputs. When 1s are written to port 0 pins, the pins can be used as high impedance inputs. Port 0 may also be configured to be the multiplex ed low order address/data bus during accesses to external program and data memor y. In this mode P0 has internal pull-ups. Port 0 also receives the code bytes du ring 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 bidirectional I/O port with internal pull-ups.The Port 1 output buffers ca n sink/source four TTL inputs. When 1s are written to Port 1 pins they are pulle d high by the internal pull-ups and can be used as inputs. As inputs, Port 1 pin s 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 bidirectional I/O port with internal pull-ups. The Port 2 output buffers can sink/source four TTL input s. When 1s are written to Port 2 pins they are pulled high by the internal pullups 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 em its the high-order address byte during fetches from external program memory and during accesses to external data memory that use 16-bit addresses (MOVX @ DPTR). In this application it uses strong internal pull-ups. When emitting 1s. During accesses to external data memory that use 8-bit addresses (MOVX @ RI), Port 2 em its the contents of the P2 Special Function Register. Port 2 also receives the h igh-order address bits and some control signals during Flash programming and ver ification. Port 3 Port 3 is an 8-bit bidirectional I/O port with internal pull-u ps. The Port 3 output buffers can sink/source four TTL inputs. When 1s are writt en 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 sour ce current (IIL) because of the pull-ups. Port 3 also serves the functions of va rious special features of the AT89C51 as listed below: 25

Alternate Functions of PORT3 Port 3 also receives some control signals for Flash programming and verification. Port Loading and Interfacing The output buffers o f Ports 1, 2, and 3 can each drive 4 LS TTL inputs. These ports on NMOS versions can be driven in a normal manner by a TTL or NMOS circuit. Both NMOS and CMOS p ins can be driven by open-collector and open-drain outputs, but note that0-to-1 transitions will not be fast. In he NMOS device, if the pin is driven by an open collector output, a 0-to-1 transition will have to be driven by the relatively w eak depletion mode FET in the CMOS device, an input 0turns off pull-up pFET3, le aving only the very weak pull-up pFET2 to drive the transition. Port 0 output bu ffers can each drive 8 LS TTL inputs. They do, however, require external pull-up s to drive NMOS inputs, except when being used as the ADDRESS/DATA bus for exter nal memory. 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 p ulse 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 n ormal operation ALE is emitted at a constant rate of 1/6 the oscillator frequenc y, 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 26

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 we akly pulled high. Setting the ALE-disable bit has no effect if the microcontroll er is in external execution mode. PSEN Program Store Enable is the read strobe t o external program memory. When the AT89C51 is executing code from external prog ram memory, PSEN is activated twice each machine cycle, except that two PSEN act ivations 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 fetc h code from external program memory locations starting at 0000H up to FFFFH. Not e, however, that if lock bit 1 is programmed, EA will be internally latched on r eset. EA should be strapped to VCC for internal program executions. This pin als o receives the 12-volt programming enable voltage (VPP) during Flash programming , for parts that require 12-volt VPP. XTAL1 Input to the inverting oscillator am plifier and input to the internal clock operating circuit. XTAL2 Output from the inverting oscillator is amplifier. Oscillator Characteristics XTAL1 and XTAL2 a re the input and output, respectively, of an inverting amplifier, which can be c onfigured for use as an on-chip oscillator, as shown in Figure 21. Either a quar tz crystal or ceramic resonator may be used. To drive the device from an externa l clock source, XTAL2 should be left unconnected while XTAL1 is driven as shown in Fig 6.2.3. 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-b y-two flip-flop, but minimum and maximum voltage high and low time specification s must be observed. 27

Idle Mode In idle mode, the CPU puts itself to sleep while all the on chip perip herals remain active. The mode is invoked by software. The content of the on-chi p RAM and all the special functions registers remain unchanged during this mode. The idle mode can be terminated by any enabled interrupt or by a hardware reset . It should be noted that when idle is terminated by a hard ware reset, the devi ce normally resumes program execution, from where it left off, up to two machine cycles before the internal reset algorithm takes control. On-chip hardware inhi bits access to internal RAM in this event, but access to the port pins is not in hibited. To eliminate the possibility of an unexpected write to a port pin when Idle is terminated by reset, the instruction following the one that invokes Idle should not be one that writes to a port pin or to external memory. Fig 6.2.3 External Clock Drive Configuration Tab 6.2.2 Status of External Pins Power down Mode In the power down mode the osc illator is stopped, and the instruction that invokes power down is the last inst ruction executed. The on-chip RAM and Special Function Registers retain their va lues until the power down mode is terminated. The only exit from 28

power down is a hardware reset. Reset redefines the SFRs but does not change the on-chip RAM. The reset should not be activated before VCC is restored to its no rmal operating level and must be held active long enough to allow the oscillator to restart and stabilize. Power on reset: When power is turned on, the circuit holds the RST pin high for an amount of time that depends on the capacitor value and the rate at which it charges. To ensure a valid reset, the RST pin must be held high long enough to allow the oscillator to start up plus two machine cycle s. On power up, Vcc should rise within approximately 10ms. The oscillator startup time depends on the oscillator frequency. For a 10 MHz crystal, the start-up time is typically 1ms.With the given circuit, reducing Vcc quickly to 0 causes t he RST pin voltage to momentarily fall below 0V. How ever, this voltage is inter nally l limited and will not harm the device. Memory organization: * Logical Sep aration of Program and Data Memory * All Atmel Flash micro controllers have sepa rate address spaces for program and Data memory as shown in Fig 1.The logical se paration of program and data memory Allows the data memory to be accessed by 8 b it addresses. This can be more quickly Stored and manipulated by an 8 bit CPU Ne vertheless 16 Bit data memory addresses Can also be generated through the DPTR r egister. Program memory can only be read. There can be up to 64K bytes of direct ly addressable program memory. The read strobe for external program memory is th e Program Store Enable Signal (PSEN) Data memory occupies a separate address spa ce from program memory. Up to 64K bytes of external memory can be directly addre ssed in the external data memory space. The CPU generates read and write signals , RD and Wr, during external data memory accesses. External program memory and e xternal data memory can be combined by applying the RD and PSEN signals to the i nputs of AND gate and using the output of fate as the read strobe to the externa l program/data memory. Program memory: Fig 1.1 shows the map of the lower part o f the program memory, after reset, the CPU begins execution from location 0000h. As shown in Fig 1.1 each interrupt is assigned a fixed location in program memo ry. The interrupt causes the CPU to jump to that location, where 29 the

it executes the service routine. External Interrupt 0 for example, is assigned t o location 0003h. If external Interrupt 0 is used, its service routine must begi n at location 0003h. If the I interrupt in not used its service location is avai lable as general-purpose program memory. Fig.2: Program Memory. 0033h Timer 2 Se rial Port Timer 1 External Interrupt 1 Timer 0 External Interrupt 0 Reset 0003h 0000h 0013h 000Bh 001Bh 8 Bytes 002Bh 0023h The interrupt service locations are spaced at 8 byte intervals 0003h for Externa l interrupt 0, 000Bh for Timer 0, 0013h for External interrupt 1,001Bh for Timer 1, and so on. If an Interrupt service routine is short enough (as is often the c ase in control applications) it can reside entirely within that 8-byte interval. Longer service routines can use a jump instruction to skip over subsequent inte rrupt locations. If other interrupts are in use. The lowest addresses of program memory can be either in the on-chip Flash or in an external memory. To make thi s selection, strap the External Access (EA) pin to either Vcc or GND. For exampl e, in the AT89C51 with 4K bytes of on-chip Flash, if the EA pin is strapped to V cc, program fetches to addresses 0000h through 0FFFh are directed to internal Fl ash. Program fetches to addresses 1000h through FFFFh are directed to external m emory. Data memory: The Internal Data memory is dived into three blocks namely, Refer Fig (1.1.1) The lower 128 Bytes of Internal RAM. The Upper 128 Bytes of In ternal RAM. Special Function Register. 30

FFh Upper 128 Accessible Accessible By Indirect By Direct Addressing Addressing 80h only. 79h Accessible By Direct and Indirect Addressing Special Function Register (Ports, S tatus and Control Bits) Lower 128 00h Internal Data memory Addresses are always 1 byte wide, which implies an address space of only 256 bytes. However, the addressing modes for internal RAM can in f act accommodate 384 bytes. Direct addresses higher than 7Fh access one memory sp ace, and indirect addresses higher than 7Fh access a different Memory Space. The lowest 32 bytes are grouped into 4 banks of 8 registers. Program instructions c all out these registers as R0 through R7. Two bits in the Program Status Word (P SW) Select, which register bank, is in use. This architecture allows more effici ent use of code space, since register instructions are shorter than instructions that use direct addressing. The next 16-bytes above the register banks form a b lock of bit addressable memory space. The micro controller instruction set inclu des a wide selection of single - bit instructions and this instruction can direc tly address the 128 bytes in this area. These bit addresses are 00h through 7Fh. either direct or indirect addressing can access all of the bytes in lower 128 b ytes. Indirect addressing can only access the upper 128. The upper 128 bytes of RAM are only in the devices with 256 bytes of RAM. The Special Function Register includes Port latches, timers, peripheral controls etc., direct addressing can only access these register. In general, all Atmel micro controllers have the sam e SFRs at the same addresses in SFR space as the AT89C51 and other compatible mi cro controllers. However, upgrades to the AT89C51 have additional SFRs. Sixteen addresses in SFR space are both byte and bit Addressable. The bit Addressable SF Rs are those whose address ends in 000B. The bit addresses in this area are 80h through FFh. FFFFh FFFFh External External 31

FFh EA = 0 External PSEN Fig.1.1 89C51 MEMORY STRUCTURE ADDRESSING MODES: Direct addressing: In direct addressing, the operand specified by an 8-bit address fie ld in the instruction. Only internal data RAM and SFRs can be directly addressed. Indirect addressing: In Indirect addressing, the instruction specifies a regist er that contains the address of the operand. Both internal and external RAM can indirectly address. The address register for 8-bit addresses can be either the S tack Pointer or R0 or R1 of the selected register Bank. The address register for 16-bit addresses can be only the 16-bit data pointer register, DPTR. Indexed ad dressing: Program memory can only be accessed via indexed addressing this addres sing mode is intended for reading look-up tables in program memory. A 16 bit bas e register (Either DPTR or the Program Counter) points to the base of the table, and the accumulator is set up with the table entry number. Adding the Accumulat or data to the base pointer forms the address of the table entry in program memo ry. Another type of indexed addressing is used in the case jump instructions. In this case the destination address of a jump instruction is computed as the sum o f the base pointer and the Accumulator data. EA = 1 External -000000h RD WR 0000 h Register instruction: 32

The register banks, which contains registers R0 through R7, can be accessed by i nstructions whose opcodes carry a 3-bit register specification. Instructions tha t access the registers this way make efficient use of code, since this mode elim inates an address byte. When the instruction is executed, one of four banks is s elected at execution time by the row bank select bits in PSW. Register - specifi c instruction: Some Instructions are specifiec to a certain register. For exampl e some instruction always operates on the Accumulator, so no address byte is nee ded to point OT ir. Inthese cases, the opcode itself points to the correct regis ter. Instruction that regger to Accumulator as A assemble as Accumulator - speci fic Opcodes. PROGRAM STATUS WORD: Program Status Word Register in Atmel Flash Mi cro controller: CY PSW 7 PSW 6 PSW 5 PSW 4 PSW0: PSW1: PSW2: PSW3: PSW4: PSW5: P SW6: PSW7: AC F0 RS1 RS0 OV --P PSW 0 PSW 1 PSW 2 PSW 3 Parity of Accumulator Set By Hardware To 1 if it contains an Odd number of 1s, o therwise it is reset to 0. User Definable Flag Overflow Flag Set By Arithmetic O perations Register Bank Select Register Bank Select General Purpose Flag. Auxili ary Carry Flag Receives Carry Out from Bit 1 of Addition Operands Carry Flag Rec eives Carry Out From Bit 1 of ALU Operands. 33

The Program Status Word contains Status bits that reflect the current state of t he CPU. The PSW shown if Fig resides in SFR space. The PSW contains the Carry Bi t, The auxiliary Carry (For BCD Operations) the two - register bank select bits, the Overflow flag, a Parity bit and two user Definable status Flags. The Carry Bit, in addition to serving as a Carry bit in arithmetic operations also serves the as the Accumulator for a number of Boolean Operations .The bits RS0 and RS1 se lect one of the four register banks. A number of instructions register to these RAM locations as R0 through R7. The status of the RS0 and RS1 bits at execution time determines which of the four banks is selected. The Parity bit reflect the Number of 1s in the Accumulator .P=1 if the Accumulator contains an even number of 1s, and P=0 if the Accumulator contains an even number of 1s. Thus, the numbe r of 1s in the Accumulator plus P is always even. Two bits in the PSW are uncomm itted and can be used as general-purpose status flags. Immediate constants: The value of a constant can follow the opcode in program memory For example. MOV A, #100 loads the Accumulator with the decimal number 100. The same number could be specified in hex digit as 64h. Oscillator and clock circuit: XTAL1 and XTAL2 ar e the input and output respectively of an inverting amplifier which is intended for use as a crystal oscillator in the pioerce configuration, in the frequency r ange of 1.2 Mhz to 12 Mhz. XTAL2 also the input to the internal clock generator. To drive the chip with an internal oscillator, one would ground XTAL1 and XTAL2 . Since the input to the clock generator is dividing by two flip flops there are no requirements on the duty cycle of the external oscillator signal. However, m inimum high and low times must be observed. The clock generator divides the osci llator frequency by 2 and provides a tow phase clock signal to the chip. The pha se 1 signal is active during the first half to each clock period and the phase 2 signals are active during the second half of each clock period. 34

CPU Timing: A machine cycle consists of 6 states. Each stare is divided into a p hase / half, during which the phase 1 clock is active and phase 2 half. Arithmet ic and Logical operations take place during phase1 and internal register - to re gister transfer take place during phase 2 Timers: The 8051 comes equipped with two timers, both of which may be controlled, set, r ead, and configured individually. The 8051 timers have three general functions: 1) Keeping time and/or calculating the amount of time between events, 2) Countin g the events themselves, or 3) Generating baud rates for the serial port. The th ree timer uses are distinct so we will talk about each of them separately. The f irst two uses will be discussed in this chapter while the use of timers for baud rate generation will be discussed in the chapter relating to serial ports. How does a timer count? How does a timer count? The answer to this question is very simple: A timer always counts up. It doesnt matter whether the timer is being use d as a timer, a counter, or a baud rate generator: A timer is always incremented by the microcontroller. Programming Tip: Some derivative chips actually allow t he program to configure whether the timers count up or down. However, since this option only exists on some derivatives it is beyond the scope of this tutorial which is aimed at the standard 8051. It is only mentioned here in the event that you absolutely need a timer to count backwards, you will know that you may be a ble to find an 8051-compatible microcontroller that does it. USING TIMERS TO MEA SURE TIME Obviously, one of the primary uses of timers is to measure time. We wi ll discuss this use of timers first and will subsequently discuss the use of tim ers to count events. When a timer is used to measure time it is also called an " interval timer" since it is measuring the time of the interval between two event s. How long does a timer take to count? First, its worth mentioning that when a t imer is in interval timer mode (as opposed to event counter mode) and correctly configured, it will increment by 1 every machine cycle. As you will recall from the previous chapter, a single machine cycle consists of 12 crystal pulses. Thus a running timer will be incremented: 11,059,000 / 12 = 921,583 35

921,583 times per second. Unlike instructions--some of which require 1 machine c ycle, others 2, and others 4--the timers are consistent: They will always be inc remented once per machine cycle. Thus if a timer has counted from 0 to 50,000 yo u may calculate: 50,000 / 921,583 = .0542 .0542 seconds have passed. In plain En glish, about half of a tenth of a second, or onetwentieth of a second. Obviously its not very useful to know .0542 seconds have passed. If you want to execute an event once per second youd have to wait for the timer to count from 0 to 50,000 18.45 times. How can you wait "half of a time?" You cant. So we come to another i mportant calculation. Lets say we want to know how many times the timer will be i ncremented in .05 seconds. We can do simple multiplication: .05 * 921,583 = 46,0 79.15. This tells us that it will take .05 seconds (1/20th of a second) to count from 0 to 46,079. Actually, it will take it .049999837 seconds--so were off by . 000000163 seconds--however, thats close enough for government work. Consider that if you were building a watch based on the 8051 and made the above assumption yo ur watch would only gain about one second every 2 months. Again, I think thats ac curate enough for most applications--I wish my watch only gained one second ever y two months. Obviously, this is a little more useful. If you know it takes 1/20 th of a second to count from 0 to 46,079 and you want to execute some event ever y second you simply wait for the timer to count from 0 to 46,079 twenty times; t hen you execute your event, reset the timers, and wait for the timer to count up another 20 times. In this manner you will effectively execute your event once p er second, accurate to within thousandths of a second. Thus, we now have a syste m with which to measure time. All we need to review is how to control the timers and initialize them to provide us with the information we need. Timer SFRs: As mentioned before, the 8051 has two timers which each function essentially the sa me way. One timer is TIMER0 and the other is TIMER1. The two timers share two SF Rs 36

(TMOD and TCON) which control the timers, and each timer also has two SFRs dedic ated solely to itself (TH0/TL0 and TH1/TL1). The TMOD SFR: The TMOD SFR is used to control the mode of operation of both time rs. Each bit of the SFR gives the microcontroller specific information concernin g how to run a timer. The high four bits (bits 4 through 7) relate to Timer 1 wh ereas the low four bits (bits 0 through 3) perform the exact same functions, but for timer 0. The individual bits of TMOD have the following functions: 37

As you can see in the above chart, four bits (two for each timer) are used to sp ecify a mode of operation. The modes of operation are: 13-bit Time Mode (mode 0): Timer mode "0" is a 13-bit timer. When the timer is i n 13-bit mode, TLx will count from 0 to 31. When TLx is incremented from 31, it will "reset" to 0 and increment THx. Thus, effectively, only 13 bits of the two timer bytes are being used: bits 0-4 of TLx and bits 0-7 of THx. This also means , in essence, the timer can only contain 8192 values. If you set a 13-bit timer to 0, it will overflow back to zero 8192 machine cycles later. 38

16-bit Time Mode (mode 1): Timer mode "1" is a 16-bit timer. This is a very comm only used mode. It functions just like 13-bit mode except that all 16 bits are u sed. TLx is incremented from 0 to 255. When TLx is incremented from 255, it rese ts to 0 and causes THx to be incremented by 1. Since this is a full 16-bit timer , the timer may contain up to 65536 distinct values. If you set a 16-bit timer t o 0, it will overflow back to 0 after 65,536 machine cycles. 8-bit Time Mode (mo de 2): Timer mode "2" is an 8-bit auto-reload mode. When a timer is in mode 2, T Hx holds the "reload value" and TLx is the timer itself. Thus, TLx starts counti ng up. When TLx reaches 255 and is subsequently incremented, instead of resettin g to 0 (as in the case of modes 0 and 1), it will be reset to the value stored i n THx. The benefit of auto-reload mode is, if you want the timer to always have a value from 200 to 255. If you use mode 0 or 1, youd have to check in code to se e if the timer had overflowed and, if so, reset the timer to 200. This takes pre cious instructions of execution time to check the value and/or to reload it. Whe n you use mode 2 the microcontroller takes care of this for you. Once youve confi gured a timer in mode 2 you dont have to worry about checking to see if the timer has overflowed nor do you have to worry about resetting the value--the microcon troller hardware will do it all for you. The auto-reload mode is very commonly u sed for establishing a baud rate for serial transmission and receiving. Split Timer Mode (mode 3): Timer mode "3" is a split-timer mode. When Timer 0 is placed in mode 3, it essentially becomes two separate 8-bit timers. That is to say, Timer 0 is TL0 and Timer 1 is TH0. Both timers count from 0 to 255 and over flow back to 0. All the bits that are related to Timer 1 will now be tied to TH0 . While Timer 0 is in split mode, the real Timer 1 (i.e. TH1 and TL1) can be put into modes 0, 1 or 2 normally--however, you may not start or stop the real time r 1 since the bits that do that are now linked to TH0. The real timer 1, in this case, will be incremented every machine cycle no matter what. The only real use of split timer mode is if you need to have two separate timers and, additionall y, a baud rate generator. In such case you can use the real Timer 1 as a baud ra te generator and use TH0/TL0 as two separate timers. The TCON SFR: 39

There is one more SFR that controls the two timers and provides valuable informa tion about them. The TCON SFR has the following structure: As you may notice, weve only defined 4 of the 8 bits. Thats because the other 4 bi ts of the SFR dont have anything to do with timers--they have to do with Interrup ts and they will be discussed in the chapter that addresses interrupts. Initiali zing a timer: As youll recall, we first must decide what mode we want the timer t o be in. In this case we want a 16-bit timer that runs continuously; that is to say, it is not dependent on any external pins. We must first initialize the TMOD SFR. Since we are working with timer 0 we will be using the lowest 4 bits of TM OD. The first two bits, GATE0 and C/T0 are both 0 since we want the timer to be independent of the external pins. 16-bit mode is timer mode 1 so we must clear T 0M1 and set T0M0. Effectively, the only bit we want to turn on is bit 0 of TMOD. Thus to initialize the timer we execute the instruction: MOV TMOD,#01h Timer 0 is now in 16-bit timer mode. However, the timer is not running. To start the tim er running we must set the TR0 bit, we can do that by executing the instruction: SETB TR0 Upon executing these two instructions timer 0 will immediately begin c ounting, being incremented once every machine cycle (every 12 crystal pulses). D etecting Timer Overflow: Often it is necessary to just know that the timer has r eset to 0. That is to say, you are not particularly interest in the value of the timer but rather you are interested in knowing 40

when the timer has overflowed back to 0. Whenever a timer overflows from its high est value back to 0, the microcontroller automatically sets the TFx bit in the T CON register. This is useful since rather than checking the exact value of the t imer you can just check if the TFx bit is set. If TF0 is set it means that timer 0 has overflowed; if TF1 is set it means that timer 1 has overflowed. We can us e this approach to cause the program to execute a fixed delay. Timers as Event c ounters: The 8051 provides us with a way to use the timers to count events. If w e want to use Timer 0 to count the number of events, set the C/T0 bit of the TMO D SFR. However, if we set C/T0, timer 0 will monitor the P3.4 line. Instead of b eing incremented every machine cycle, timer 0 will count events on the P3.4 line . So if we connect any sensor to P3.4 and let the 8051 do the work. Then, when w e want to know how many have occurred, we just read the value of timer 0. The va lue of timer 0 will be the number of events that have occurred. The 8051 counts one to zero transitions on the P3.4 line. This means that when there is a raise on the P3.4 pin the 8051 will not count anything since this is a 0-1 transition. However, when the sensor will fall back to a low ("0") state. This is a 1-0 tra nsition and at that instant the counter will be incremented by 1. It is importan t to note that the 8051 checks the P3.4 line each instruction cycle (12 clock cy cles). This means that if P3.4 is low, goes high, and goes back low in 6 clock c ycles it will probably not be detected by the 8051. This also means the 8051 eve nt counter is only capable of counting events that occur at a maximum of 1/24th the rate of the crystal frequency. That is to say, if the crystal frequency is 1 2.000 MHz it can count a maximum of 500,000 events per second (12.000 MHz * 1/24 = 500,000). If the event being counted occurs more than 500,000 times per secon d it will not be able to be accurately counted by the 8051. SERIAL COMMUNICATION THEORY: In order to connect micro controller to a modem or a pc to modem a seria l port is used. Serial is a very common protocol for device communication that i s standard on almost every PC. Most computers include two RS-232 based serial po rts. Serial is also a common communication protocol that is used by many devices for instrumentation; numerous GPIBcompatible devices also come with an RS-232 p ort. Furthermore, serial communication can be used for data acquisition in conju nction with a remote sampling device. 41

The concept of serial communication is simple. The serial port sends and receive s bytes of information one bit at a time. Although this is slower than parallel communication, which allows the transmission of an entire byte at once, it is si mpler and can be used over longer distances. For example, the IEEE 488 specifica tions for parallel communication state that the cabling between equipment can be no more than 20 meters total, with no more than 2 meters between any two device s. Serial, however, can extend as much as 1200 meters. Typically, serial is used to transmit ASCII data. Communication is completed using 3 transmission lines: (1) Ground, (2) Transmit, and (3) Receive. Since serial is asynchronous, the por t is able to transmit data on one line while receiving data on another. Other li nes are available for handshaking, but are not required. The important serial ch aracteristics are baud rate, data bits, stop bits, and parity. For two ports to communicate, these parameters must match. Baud rate: It is a speed measurement f or communication. It indicates the number of bit transfers per second. For examp le, 300 baud is 300 bits per second. When a clock cycle is referred it means the baud rate. For example, if the protocol calls for a 4800 baud rate, then the cl ock is running at 4800Hz. This means that the serial port is sampling the data l ine at 4800Hz. Common baud rates for telephone lines are 14400, 28800, and 33600 . Baud rates greater than these are possible, but these rates reduce the distanc e by which devices can be separated. These high baud rates are used for device c ommunication where the devices are located together, as is typically the case wi th GPIB devices. Data bits: Measurement of the actual data bits in a transmission. When the compu ter sends a packet of information, the amount of actual data may not be a full 8 bits. Standard values for the data packets are 5, 7, and 8 bits. Which setting chosen depends on what information transferred? For example, standard ASCII has values from 0 to 127 (7 bits). Extended ASCII uses 0 to 255 (8 bits). If the dat a being transferred is simple text (standard ASCII), then sending 7 bits of data per packet is sufficient for communication. A packet refers to a single byte tr ansfer, including start/stop bits, data bits, and parity. Since the number of ac tual bits depends on the protocol selected, the term packet is used to cover all instances. 42

Stop bits: It is used to signal the end of communication for a single packet. Ty pical values are 1, 1.5, and 2 bits. Since the data is clocked across the lines and each device has its own clock, it is possible for the two devices to become slightly out of sync. Therefore, the stop bits not only indicate the end of tran smission but also give the computers some room for error in the clock speeds. Th e more bits that are used for stop bits, the greater the lenience in synchronizi ng the different clocks, but the slower the data transmission rate. Parity: It i s simple form of error checking that is used in serial communication. There are four types of parity: even, odd, marked, and spaced. The option of using no pari ty is also available. For even and odd parity, the serial port sets the parity b it (the last bit after the data bits) to a value to ensure that the transmission has an even or odd number of logic high bits. For example, if the data is 011, then for even parity, the parity bit is 0 to keep the number of logic-high bits even. If the parity is odd, then the parity bit is 1, resulting in 3 logic-high bits. Marked and spaced parity does not actually check the data bits, but simply sets the parity bit high for marked parity or low for spaced parity. This allow s the receiving device to know the state of a bit to enable the device to determ ine if noise is corrupting the data or if the transmitting and receiving device clocks are out of sync. WHAT IS RS 232C RS-232 (ANSI/EIA-232 Standard) is the ser ial connection found on IBM-compatible PCs. It is used for many purposes, such a s connecting a mouse, printer, or modem, as well as industrial instrumentation. Because of improvements in line drivers and cables, applications often increase the performance of RS-232 beyond the distance and speed listed in the standard. RS-232 is limited to point-to-point connections between PC serial ports and devi ces. RS-232 hardware can be used for serial communication up to distances of 50 feet . DB-9 pin connector 12345 6789 43

(Out of computer and exposed end of cable) Pin Functions: Data: Handshake: Commo n: Other: TxD on pin 3, RxD on pin 2 RTS on pin 7, CTS on pin 8, DSR on pin 6, C D on pin 1, DTR on pin 4 Common pin 5(ground) RI on pin 9 The method ree lines: unications rom DCE to used by RS-232 for communication allows for a simple connection of th Tx, Rx, and Ground. The three essential signals for 2 way RS-232 Comm are these: TXD: carries data from DTE to the DCE. RXD: carries data f the DTE SG: signal ground

Connection Diagram: SFRs Used for Serial Communication: SCON: TMOD: SM2 SM1 44 T1: Embedded TH1

BAUD RATE CALCULATION: Internal timer stages are as follows XClk Divided by X box can be replaced with T1 timer so that by changing the value of timer we can obtain the required baud rate. Let XClk Baud Rate = = 11.0592 Mhz ( XClk / 12 / 16 / 2 / X ) For attaining 9600 baud Rate X can be calculated = 11.0 592 x 106 / 12 / 16 / 2 / 9600 = 3 So set the 2s Complement of 3 in Timer 1 so th at we can achieve 9600 baud rates. Note: Assuming 8-bit Auto reload mode and 8-b it variable baud rate modes. D b FLOW CHART: TX Loop: 45

RX Loop: Initialization: Load SFRs w MAX 232 Introduction: Copy data Initialization: (or) m Load SFRs wit 46

Serial RS-232 (V.24) communication works with voltages (-15V ... -3V for high [s ic]) and +3V ... +15V for low [sic]) which are not compatible with normal comput er logic voltages. On the other hand, classic TTL computer logic operates betwee n 0V ... +5V (roughly 0V ... +0.8V for low, +2V ... +5V for high). Modern low-po wer logic operates in the range of 0V ... +3.3V or even lower. o, the maximum RS -232 signal levels are far too high for computer logic electronics, and the nega tive RS-232 voltage for high . Therefore, to receive serial data from an RS-232 interface the voltage has to be reduced, and the low and high voltage level inve rted. In the other direction (sending data from some logic over RS-232) the low logic voltage has to be "bumped up", and a negative voltage has to be generated, too. Logic Voltages ll this can be done with conventional analog electronics, e .g. a particular power supply and a couple of transistors or the once popular 14 88 (transmitter) and 1489 (receiver) ICs. However, since more than a decade it h as become standard in amateur electronics to do the necessary signal level conve rsion with an integrated circuit (IC) from the MAX232 family (typically a MAX232 A or some clone). In fact, it is hard to find some The MAX232 & MAX232A he MAX 2 32 translates RS232 voltages to TTL voltages. RS232 represent a binary 1 or HI a nywhere between 3V to 12V, a zero logic or LOW, between 3V and 12V. TTL in the oth er hand responds to 0 to 2.1V as logic zero and 2.8V to 5V as a HI. The MAX 232 provides voltage translation so the TTL PIC 16F84 can understand the messages se nt to it from the computer. A serial cable is also provided to connect the MAX23 2 to the PC and jumper cables to connect the MAX232 to the micro controller. he MAX232 from Maxim was the first IC which in one package contains the necessary d rivers (two) and receivers (also two), to adapt the RS-232 signal voltage levels to TTL logic. It became popular, because it just needs one voltage (+5V) and ge nerates the necessary RS-232 voltage levels (approx. -10V and +10V) internally. This greatly simplified the design of circuitry. Circuitry designers no longer n eed to design and build a power supply with three voltages (e.g. -12V, +5V, and +12V), but could just provide one +5V power supply, e.g. with the help of a simp le 78x05 voltage converter. 47

MAX232 (A) DIP Package DIP Package of MAX 232A A Typical Application The MAX232 (A) has two receivers ( converts from RS-232 to TTL voltage levels) and two drivers (converts from TTL l ogic to RS-232 voltage levels). This means only two of the RS232 signals can be converted in each direction. The old MC1488/1498 combo provided four drivers and receivers. Typically a pair of a driver/receiver of the MAX232 is used for TX and RX and the second one for CTS and RTS. There are not enough drivers/receivers in the MAX232 to also connect the DTR, DS R, and DCD signals. Usually these signals can be omitted when e.g. communicating with a PC s serial interface. If the DTE really requires these signals either a second MAX232 is needed, or some other IC from the MAX232 family can be used (i f it can be found in consumer electronic shops at all). An alternative for DTR/D SR is also given below. Maxim s data sheet explains the MAX232 family in great d etail, including the pin configuration and how to connect such an IC to external circuitry. This information can be used as-is in own design to get a working RS -232 interface. Maxim s data just misses one critical piece of information: How exactly to connect the RS-232 signals to the IC. So here is one possible example : MAX232 to RS232 DB9 Connection as a DCE 48

MAX232 Pin Nbr. 7 8 9 10 11 12 13 14 15 MAX232 Pin Name T2out R2in R2out T2in T1in R1out R1in T1out GND Signal CTS RTS RTS CTS TX RX RX TX GND Voltage RS-232 RS-232 TTL TTL TTL TTL RS-232 RS-232 0 DB9 Pin 7 8 n/a n/a n/a n/a 2 3 5 Connections between MAX 232 & RS 232 In addition one can directly wire DTR (DB9 pin 4) to DSR (DB9 pin 6) without goi ng through any circuitry. This gives automatic (brain dead) DSR acknowledgement of an incoming DTR signal. Sometimes pin 6 of the MAX232 is hard wired to DCD (D B9 pin 1). This is not recommended. Pin 6 is the raw output of the voltage pump and inverter for the -10V voltage. Drawing currents from the pin leads to a rapi d breakdown of the voltage, and as a consequence to a breakdown of the output vo ltage of the two RS-232 drivers. It is better to use software which doesn t care about DCD, but does hardware-handshaking via CTS/RTS only. The circuitry is com pleted by connecting five capacitors to the IC as it follows. The MAX232 needs 1 .0F capacitors, the MAX232A needs 0.1F capacitors. MAX232 clones show similar diff erences. It is recommended to consult the corresponding data sheet. At least 16V capacitor types should be used. If electrolytic or tantalic capacitors are used , the polarity has to be observed. The first pin as listed in the following tabl e is always where the plus pole of the capacitor should be connected to. Externa l Capacitors connected to+5V: Pin 16 GND: Pin 15 The 5V power supply is MAX232(A) external Capacitors Capacitor + Pin - Pin Remark C1 1 3 C2 4 5 C3 2 16 C4 GND 6 This looks non-intuitive, but because pin 6 is 49

on -10V, GND gets the + connector, and not the C5 16 GND Drawbacks of MAX232: The MAX-232 chip receives data from the receiver, and converts it to the standar d RS-232 data format that can be read in by a serial port on a personal computer or workstation. For the RS-232 interface, a standard MAX232 chip is used for le vel conversion. Both use the on chip USART and thus the same firmware. CONNECTIO NS IN MAX 232: If you wanted to do a general RS-232 connection, you could take a bunch of long wires and solder them directly to the electronic circuits of the equipment you are using, but this tends to make a big mess and often those solde r connections tend to break and other problems can develop. To deal with these i ssues, and to make it easier to setup or take down equipment, some standard conn ectors have been developed that is commonly found on most equipment using the RS -232 standards. These connectors come in two forms: A male and a female connecto r. The female connector has holes that allow the pins on the male end to be inse rted into the connector. This is a female "DB-9" connector (properly known as DE 9F): Fig.6.5.1 Female Connector The female DB-9 connector is typically used as the "plug" that goes into a typic al PC. If you see one of these on the back of your computer, it is likely not to be used for serial 50

communication, but rather for things like early VGA or CGA monitors (not SVGA) o r for some special control/joystick equipment. And this is a male "DB-9" connect or (properly known as DE9M): Fig 6.5.2 Male Connector This is the connector that you are more likely to see for serial communications on a "generic" PC. Often you will see two of them side by side (for COM1 and COM 2). Special equipment that you might communicate with would have either connecto r, or even one of the DB-25 connectors listed below. The wiring of RS-232 device s involves first identifying the actual pins that are being used. Here is how a female DB-9 connector is numbered: If the numbers are hard to read, it starts at the top-right corner as "1", and g oes left until the end of the row and then starts again as pin 6 on the next row until you get to pin 9 on the bottom-left pin. "Top" is defined as the row with 5 pins. The male connector (like what you have on your PC) is simply this same order, but reversed from right to left. Here each pin is usually defined as: 1 9-pin 25-pin pin definition 8 DCD (Data Carrier Detect) 51

2 3 4 5 6 7 8 9 3 2 20 7 6 4 5 22 RX (Receive Data) TX (Transmit Data) DTR (Data Terminal Ready) GND (Signal Groun d) DSR (Data Set Ready) RTS (Request To Send) CTS (Clear To Send)) RI (Ring Indi cator) Tab 6.5.4 Pin Definition of Connectors One thing to keep in mind when discussing these pins and their meaning is that t hey are very closely tied together with modems and modem protocols. Often you do n t have a modem attached in the loop, but you still treat the equipment as if i t were a modem on a theoretical level. BAUD RATES: I m going to go on a bit of a rant here. Baud and BPS (Bits Per Second) are usually not the same thing, altho ugh they are often used interchangeable, particular in marketing literature. Onl y originally they were the same. There are several ways to determine what the ac tual data rate of a particular piece of equipment is, but in popular marketing l iterature, or even general reference texts, they will almost always refer to "Ba ud Rate", even if they are referring to bits per second. Language purists and en gineers who know what they are talking about will go into a more literal definit ion of Baud meaning the number of changes to the transmission media per second i n a modulated signal. If each transmission event contains more than one bit of i nformation, than Baud and BPS are not the same. E.g. if each event contains two bits (two bits modulated in an event), then the BPS of such a transmission would be twice as large as the Baud rate. This is not a theoretical case. Typical "hi gh speed" modems use sophisticated modulation on the telephone line, were the bi t rate and Baud rate differ significantly on the line. It is important to know t his when you build measurement equipment, decoders (demodulators), encoders (mod ulators), and all sorts of transmission equipment for a particular protocol. 52

However, software developers typically like to ignore the difference of bit rate and baud rate, because in their small world, a bit can either have the value tr ue or false - an "event" (a bit) always only has two possible states. They have no basic unit which can e.g. hold four different states. In other words, on the software site the modulation has already been flattened by the demodulator. If a modulation was used which can e.g. transmit 8 bits in an event, the software de veloper sees them already as a series of 8 consecutive bits, each either true or false. The demodulator took care of that. When it got an event it turned the si ngle 8-bit event into eight single-bit events. Software developers don t see the original single entity with 256 different states (voltages, phases). Since the modulation has been flattened they don t experience the difference between Baud rate and bit rate any more. This is not the fault of the people who defined a Ba ud or a BPS. It is just a (welcome) limitation of digital computer hardware. Bau d is actually a shortened term named in honor of mile Baudot, a French inventor o f early teleprinter machines that replaced the telegraph key using Morse code. B asically two typewriters that could be connected to each other with some wires. He came up with some of the first digital character encoding schemes, and the ch aracter codes were transmitted with a serial data connection. Keep in mind this was being done largely before computers were invented. Indeed, some of these ear ly tele-printer devices were connected to the very first computers like the ENIA C or UNIVAC, simply because they were relatively cheap and mass produced at that point. In order for serial data communication to happen, you need to agree on a clock signal, or baud rate, in order to get everything to be both transmitted a nd received properly. This is where the language purists get into it, because it is this clock signal that actually drives the "baud rate". Let s start more at Tele printers evolved, and eventually you have Western Union sending tele-printe r "cablegrams" all around the world. If you hear of a TELEX number, this is the relic of this system, which is still in use at the present time, even with the i nternet. By rapidly glossing over a whole bunch of interesting history, you end up with the United States Department of Justice (DOJ) in a lawsuit with AT&T. Mi nd you this was an earlier anti-trust lawsuit prior to the famous/infamous 1982 settlement. The reason this is important is because the DOJ insisted that Wester n Union got all of the digital business (cable grams... and unfortunately this g ot to be read as computer equipment as well), and AT&T got modulated frequencies , or 53

in other words, you could talk to your mother on Mother s Day on their equipment . When computers were being built in the 1950s, people wanted some way to connec t different pieces of computer equipment together to "talk" to each other. This finally resulted in the RS-232 standard that we are discussing on this page. Whi le Western Union was permitted to carry digital traffic, often the connections w eren t in or near computer centers. At this time AT&T found a loophole in the an ti-trust settlement that could help get them into the business of being a "carri er" of computer data. They were also offering to transmit computer data at rates considerably cheaper than Western Union was going to charge. Hence, the modem w as born. Interrupts: As the name implies, an interrupt is some event which interrupts normal program execution. As stated earlier, program flow is always sequential, being altered o nly by those instructions which expressly cause program flow to deviate in some way. However, interrupts give us a mechanism to "put on hold" the normal program flow, execute a subroutine, and then resume normal program flow as if we had ne ver left it. This subroutine, called an interrupt handler, is only executed when a certain event (interrupt) occurs. The event may be one of the timers "overflo wing," receiving a character via the serial port, transmitting a character via t he serial port, or one of two "external events." The 8051 may be configured so t hat when any of these events occur the main program is temporarily suspended and control passed to a special section of code which presumably would execute some function related to the event that occurred. Once complete, control would be re turned to the original program. The main program never even knows it was interru pted. The ability to interrupt normal program execution when certain events occu r makes it much easier and much more efficient to handle certain conditions. If it were not for interrupts we would have to manually check in our main program w hether the timers had overflows, whether we had received another character via t he serial port, or if some external event had occurred. Besides making the main program ugly and hard to read, such a situation would make our program inefficie nt since wed be burning precious "instruction cycles" checking for events that us ually dont happen. We can configure the 8051 so that any of the following events will cause an interrupt: Timer 0 Overflow. Timer 1 Overflow. 54

Reception/Transmission of Serial Character. External Event 0. External Event 1. bviously we need to be able to distinguish between various interrupts and execut ing different code depending on what interrupt was triggered. This is accomplish ed by jumping to a fixed address when a given interrupt occurs as shown below. By consulting the above chart we see that whenever Timer 0 overflows (i.e., the TF0 bit is set), the main program will be temporarily suspended and control will jump to 000BH. It is assumed that we have code at address 000BH that handles th e situation of Timer 0 overflowing. Setting up Interrupts: By default at power up, all interrupts are disabled. This means that even if, fo r example, the TF0 bit is set, the 8051 will not execute the interrupt. Your pro gram must specifically tell the 8051 that it wishes to enable interrupts and spe cifically which interrupts it wishes to enable. Your program may enable and disa ble interrupts by modifying the IE SFR (A8h): As you can see, each of the 8051s interrupts has its own bit in the IE SFR. You e nable a given interrupt by setting the corresponding bit. However, before enabli ng any interrupt, you must set bit 7 of IE. Bit 7, the Global Interrupt Enable/D isable, enables or disables all interrupts simultaneously. That is to say, if 55

bit 7 is cleared then no interrupts will occur, even if all the other bits of IE are set. Setting bit 7 will enable all the interrupts that have been selected b y setting other bits in IE. This is useful in program execution if you have time -critical code that needs to execute. In this case, you may need the code to exe cute from start to finish without any interrupt getting in the way. To accomplis h this you can simply clear bit 7 of IE (CLR EA) and then set it after your time -critical code is done. Interrupt priorities: The 8051 automatically evaluates whether an interrupt should occur after every i nstruction. When checking for interrupt conditions, it checks them in the follow ing order: External 0 Interrupt Timer 0 Interrupt External 1 Interrupt Timer 1 I nterrupt Serial Interrupt This means that if a Serial Interrupt occurs at the ex act same instant that an External 0 Interrupt occurs, the External 0 Interrupt w ill be executed first and the Serial Interrupt will be executed once the Externa l 0 Interrupt has completed. The 8051 offers two levels of interrupt priority: h igh and low. By using interrupt priorities you may assign higher priority to cer tain interrupt conditions. Interrupt priorities are controlled by the IP SFR (B8 h). The IP SFR has the following format: When considering interrupt priorities, the following rules apply: 56

Nothing can interrupt a high-priority interrupt--not even another high priority interrupt. A high-priority interrupt may interrupt a low-priority interrupt. A l ow-priority interrupt may only occur if no other interrupt is l ready executing. If two interrupts occur at the same time, the interrupt with higher priority wi ll execute first. If both interrupts are of the same priority the interrupt whic h is serviced first by polling sequence will be executed first. When an interrupt is triggered, the following actions are taken automatically by the microcontroller: The current Program Counter is saved on the stack, low-byt e first. Interrupts of the same and lower priority are blocked. In the case of T imer and External interrupts, the corresponding interrupt flag is cleared. Progr am execution transfers to the corresponding interrupt handler address. The Inter rupt Handler Routine executes. Take special note of the third step: If the inter rupt being handled is a Timer or External interrupt, the microcontroller automat ically clears the interrupt flag before passing control to your interrupt handle r routine. This means it is not necessary that you clear the bit in your code. v ector DC GEARED MOTOR: High efficiency, high quality low cost DC motor with gearbox fo r robotics applications. Very easy to use and available in standard size. Nut an d threads on shaft to easily connect and internal threaded shaft for easily conn ecting it to wheel. Features 45 RPM 12V DC motors with Gearbox 5kgcm torque 3000RPM base motor 6mm shaft diam eter with internal hole 125gm weight Same size motor available in various rpm 57

No-load current = 60 mA(Max), Load current = 300 mA(Max) MOTOR DRIVER L293D: The L293 is an integrated circuit motor driver that can be u sed for simultaneous, bidirectional control of two small motors. Small means sma ll. The L293 is limited to 600 mA, but in reality can only handle much small cur rents unless you have done some serious heat sinking to keep the case temperatur e down. Unsure about whether the L293 will work with your motor? Hook up the cir cuit and run your motor while keeping your finger on the chip. If it gets too ho t to touch, you can t use it with your motor. (Note to ME2011 students: The L293 should be OK for your small motor but is not OK for your gear motor.) The L293 comes in a standard 16-pin, dual-in line integrated circuit package. There is an L293 and an L293D part number. Pick the "D" version because it has built in fly back diodes to minimize inductive voltage spikes. The pinout for the L293 in the 16-pin package is shown below in top view. Pin 1 is at the top left when the no tch in the package faces up. Note that the names for pin functions may be slight ly different than what is shown in the following diagrams. 58

The following schematic shows how to connect the L293 to your motor and the Stam p. Each motor takes 3 Stamp pins. If you are only using one motor, leave pins 9, 10, 11, 12, 13, 14, and 15 empty. 59

Assume you have only one motor connected with the enable tied to Stamp Pin 0, an d the two direction controls tied to Stamp Pins 1 and 2. Here is a table describ ing the control pin functions. ENABLE H H H L DIRA H L L/H either DIRB L H L/H e ither Function Turn right Turn left Fast stop Slow stop And here is a short sample program that exercises the L293. 60


Fig: shows the H-Bridge operation. The H-Bridge consists of a four PNP transisto rs such as Q1, Q2, Q3 and Q4. These transistors are arranged in a way that a DC motor M can rotate. A and B are represented as two inputs for operating a motor through the transistors. For the circuit operation, we are providing +12V DC as a VCC. The operation will be explained as follows: The inputs A and B can be app lied as a either logic 0 or logic 1 ie., may be either 5V DC voltage or Ground. If t he input A =logic 0 and B=logic1 then transistors Q1 and Q4 will be ON state and Q2 a d Q3 will be OFF state. The current flows from Q1 to Q4 so that the motor M can ro tate in clockwise direction. If the input A =logic 1 and B=logic0 then transistors Q 1 and Q4 will be OFF state and Q2 and Q3 will be ON state. The current flows from Q1 to Q4 so that the motor M can rotate in Anti-clockwise direction. If the input A =logic 1 and B=logic1 then transistors Q1 and Q4 will be OFF state and Q2 and Q3 wi l be OFF state. No current flows from in the circuit. The circuit will be in hold condition. The motor will not rotate any direction. So, there is no wastage of p ower will occur. Otherwise, if both inputs are low that is all transistors are c ome under working and more current will flows in the circuit. But the motor will be at hold condition. More power is wasted. PC: 61

The PC is generally used as the means of storing the gathered or acquired inform ation at the backend. The PC in some cases is also used as give the inputs to an Embedded System through Serial Communication. The Serial Communication between the PC and our Embedded System is done with the help of a Driver. There is a nee d to use this Line Driver between a PC and our Embedded System in order to match the Logic Levels of both. The Logic levels of PC of Serial Port are RS 232 i.e. -3 to -25 for Logic 1 and +3 to +25 for Logic 0. And the Logic Levels of our Em bedded System with Microcontroller AT 89C51 are 0.0 to 0.8 for Logic 0 and 2.0 t o 5.0 for Logic 1. Hence the PC is interfaced to microcontroller 89C51 through S erial Interface Driver -MAX 232. ZIGBEE TRANSCEIVER: Pin Diagram Fig: 6.1 Pin diagram of X-Bee Transceiver 62

Zigbee modules feature a UART interface, which allows any microcontroller or mic roprocessor to immediately use the services of the Zigbee protocol. All a Zigbee hardware designer has to do in this ase is ensure that the hosts serial port log ic levels are compatible with the XBees 2.8- to 3.4-V logic levels. The logic lev el conversion can be performed using either a standard RS-232 IC or logic level translators such as the 74LVTH125 when the host is directly connected to the XBe e UART. The below table gives the pin description of transceiver. Table: 6.1 Pin Description of X-Bee Transceiver Pin 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Name Vcc DOUT DIN/CONFIG DO8 RESET PWM0/RSSI PWM1 [reserved] DDR/SLEEP_ RQ/DI8 GND AD4/DIO4 CTS/DIO7 ON/SLEEP VREF Associate/AD5/DIO5 RTS/AD6/DIO6 AD3/D IO3 AD2/DIO2 AD1/DIO1 AD0/DIO0 Direction Output Input Output Input Output Output Input Either Either Output Input Either Either Either Either Either Either Desc ription Power Supply UART Data Out UART Data In Digital Output 8 Module Reset PW M Output 0/RX Signal Strength Indicator PWM Output 1 Do not connect Pin Sleep Co ntrol Line or Digital Input 8 Ground Analog Input 4 or Digital I/O 4 Clear-to-Se nd Flow Control or Digital I/O 7 Module Status Indicator Voltage Reference for A /D Inputs Associated Indicator, Analog Input 5 or Digital I/O 5 Request-to-Send Flow Control, Analog Input 6 or Digital I/O 6 Analog Input 3 or Digital I/O 3 An alog Input 2 or Digital I/O 2 Analog Input 1 or Digital I/O 1 Analog Input 0 or Digital I/O 0 Design Notes: 63 Minimum connections: VCC, GND, DOUT & DIN

Minimum connections for updating firmware: VCC, GND, DIN, DOUT, RTS and DTR al Direction is specified with respect to the module Module includes a 50k pull-up resistor attached to RESET Several of the input pull-ups can be configured using the PR command should be left disconnected Features Performance: Table: 6.2 Performance characteristics


Unused pins

Parameters Indoor/Urban Range Outdoor RF (LOS) Transmit Power Output RF Data Rate Serial In terface Data Rate Receiver Sensitivity Value 30m 100m 1mW (0dBm) 250,000bps 1200-115200bps -92dBm Power Requirements: Table: 6.3 Power Requirement characteristics Parameters Supply Voltage Transmit Current Receive Current Value 2.8 - 3.4V 45mA 50mA General: Table: 6.4 General characteristics Parameters Operating Frequency Dimensions Operating Temperature Antenna Options Value ISM 2.4GHz 2.468 x 2.761 -40o to 85o C Integrated Chip Antenna 64

Networking and Security: Table: 6.5 Networking and Security characteristics Parameters Supported Network Topologies Number of Channels Addressing Options Value Point-to-point, Point-to-multipoint, Peer-to-peer 16 Direct Sequence Channels PA N ID, Channel and Addresses 6.3 System Data Flow Diagram: Fig: 6.2 Data Flow Diagram The X-Bee RF Modules interface to a host device throu gh a logic-level asynchronous Serial port. Through its serial port, the module c an communicate with any logic and voltage Compatible UART; or through a level tr anslator to any serial device. Data is presented to the X-Bee module through its DIN pin, and it must be in the asynchronous serial format, which consists of a start bit, 8 data bits, and a stop bit. Because the input data goes directly int o the input of a UART within the X-Bee module, no bit inversions are necessary w ithin the asynchronous serial data stream. All of the required timing and parity checking is automatically taken care of by the X-Bees UART. Just in case you are producing data faster than the X-Bee can process and transmit it, both X-Bee mo dules incorporate a clear-to-send (CTS) function to throttle the data being pres ented to the X-Bee modules DIN pin. You can eliminate the need for the CTS signal by sending small data packets at slower data rates. 65

If the microcontroller wants to send data to transceiver, it will send RTS (Requ est to Send) signal. If the transceiver is idle it sends CTS (Clear to Send) sig nal. The RTS and CTS signals are active low. When microcontroller receives CTS c ommand it will send data to the transceiver through DIN pin. The transceiver wil l send the data to microcontroller through DOUT pin. The communication between t ransceiver and the microcontroller at the transmitter and receiver is similar. T he communication between transmitter and receiver is through RF communication. 6.4 Serial Data Fig: 6.3 Serial Data Sequence For example: UART data packet 0x1F (decimal number is 31) as transmitted through the RF module. Data enters the module UART throug h the DI pin (pin 3) as an asynchronous serial signal. The signal should idle hi gh when no data is being transmitted. Each data byte consists of a start bit (lo w), 8 data bits (least significant bit first) and a stop bit (high). The followi ng figure illustrates the serial bit pattern of data passing through the module. The module UART performs tasks, such as timing and parity checking, that are ne eded for data communications. Serial communications depend on the two UARTs to b e configured with compatible settings (baud rate, parity, start bits, stop bits, data bits). X-Bee RF Modules operate in Transparent Mode. When operating in thi s mode, the modules act as a serial line replacement - all UART data received th rough the DI pin is queued up for RF transmission. When RF data is received, the data is sent out the DO pin. 66

Serial-to-RF Packetization Data is buffered in the DI buffer until one of the following causes the data to be packetized and transmitted: No serial characters are received for the amount of time determined by the RO (Packetization Timeout) parameter. If RO = 0, packe tization begins when a character is received. The maximum number of characters t hat will fit in an RF packet (100) is received. The Command Mode Sequence (GT + CC + GT) is received. Any character buffered in the DI buffer before the sequence is transmitted. If the module cannot immedi ately transmit (for instance, if it is already receiving RF data), the serial da ta is stored in the DI Buffer. The data is packetized and sent at any RO timeout or when 100 bytes (maximum packet size) are received. If the DI buffer becomes full, hardware or software flow control must be implemented in order to prevent overflow (loss of data between the host and module). 6.5 Internal Data Flow Fig: 6.4 Internal Data Flow Diagram DI (Data In) Buffer: 67

When serial data enters the RF module through the DI pin (pin 3), the data is st ored in the DI Buffer until it can be processed. Hardware Flow Control (CTS): Wh en the DI buffer is 17 bytes away from being full; by default, the module deasse rts CTS (high) to signal to the host device to stop sending data [refer to D7 (D IO7 Configuration) parameter]. CTS are re-asserted after the DI Buffer has 34 by tes of memory available. How to eliminate the need for flow control: Send messag es that are smaller than the DI buffer size. Interface at a lower baud rate [BD (Interface Data Rate) parameter] than the throughput data rate. Case in which th e DI Buffer may become full and possibly overflow: If the module is receiving a continuous stream of RF data, any serial data that arrives on the DI pin is plac ed in the DI Buffer. The data in the DI buffer will be transmitted overthe-air w hen the module is no longer receiving RF data in the network. DO (Data Out) Buff er: When RF data is received, the data enters the DO buffer and is sent out the serial port to a host device. Once the DO Buffer reaches capacity, any additiona l incoming RF data is lost. Hardware Flow Control (RTS): If RTS is enabled for f low control (D6 (DIO6 Configuration) Parameter = 1), data will not be sent out t he DO Buffer as long as RTS (pin 16) is de-asserted. Two cases in which the DO B uffer may become full and possibly overflow: If the RF data rate is set higher t han the interface data rate of the module, the module will receive data from the transmitting module faster than it can send the data to the host. If the host d oes not allow the module to transmit data out from the DO buffer because of bein g held off by hardware or software flow control. 68

6.6 I/O Data Format I/O data begins with a header. The first byte of the header defines the number o f samples forthcoming. A sample is comprised of input data and the inputs can cont ain either DIO or ADC. The last 2 bytes of the header (Channel Indicator) define which inputs are active. Each bit represents either a DIO line or ADC channel. Fig: 6.5 Header of I/O Data Format Sample data follows ine how to read the 2 bytes are the DIO an unsigned 10-bit the header and the channel indicator frame is used to determ sample data. If any of the DIO lines are enabled, the first data and the ADC data follows. ADC channel data is stored as value rightjustified on a 16-bit boundary. Sample Data

Fig: 6.6 Sample Data of I/O Data Format 6.7 Networks: The following IEEE 802.15.4 network types are supported by the Zigbee RF modules : NonBeacon NonBeacon (w/ Coordinator) The following terms will be used to expli cate the network operations: 69

Table 6.6: Terms and definitions: Term PAN Coordinator End Device Definition Per sonal Area Network - A data communication network that includes one or more End Devices and optionally a Coordinator. A Full-function device (FFD) that provides network synchronization by polling nodes [NonBeacon (w/ Coordinator) networks o nly] When in the same network as a Coordinator - RF modules that rely on a Coord inator for synchronization and can be put into states of Association sleep for l ow-power applications. The establishment of membership between End Devices and a Coordinator. Association is only applicable in NonBeacon (w/Coordinator) networ ks. 6.7.1NonBeacon: By default, XBee/XBee-PRO RF Modules are configured to suppo rt NonBeacon communications. NonBeacon systems operate within a Peer-to-Peer net work topology and therefore are not depen-dent upon Master/Slave relationships. This means that modules remain synchronized without use of master/server configu rations and each module in the network shares both roles of master and slave. Ma xStream s peer-to-peer architecture features fast synchronization times and fast cold start times. This default configuration accommodates a wide range of RF da ta applications. A peer-to-peer network can be established by configuring each m odule to operate as an End Device (CE = 0), disabling End Device Association on all modules (A1 = 0) and setting ID and CH parameters to be identical across the network. Figure 6.7: NonBeacon Peer-to-Peer Architecture 6.7.2 NonBeacon (w/ Coordinator) : 70

A device is configured as a Coordinator by setting the CE (Coordinator Enable) p arameter to 1. Coordinator power-up is governed by the A2 (Coordinator Association ) parameter. In a NonBeacon (w/ Coordinator) system, the Coordinator can be conf igured to use direct or indi-rect transmissions. If the SP (Cyclic Sleep Period) parameter is set to 0, the Coordinator will send data immediately. Otherwise, the SP parameter determines the length of time the Coordinator will retain the data before discarding it. Generally, SP (Cyclic Sleep Period) and ST (Time before S leep) parameters should be set to match the SP and ST settings of the End Device s. 6.7.3 Association: Association is the establishment of membership between End Devices and a Coordinator and is only applicable in NonBeacon (w/ Coordinator) networks. The establishment of membership is useful in scenarios that require a central unit (Coordinator) to relay messages to or gather data from several remo te units (End Devices), assign channels or assign PAN IDs. An RF data network th at consists of one Coordinator and one or more End Devices forms a PAN (Personal Area Network). Each device in a PAN has a PAN Identifier [ID (PAN ID) parameter ]. PAN IDs must be unique to prevent miscommunication between PANs. The Coordina tor PAN ID is set using the ID (PAN ID) and A2 (Coordinator Association) command s. An End Device can associate to a Coordinator without knowing the address, PAN ID or channel of the Coordinator. The A1 (End Device Association) parameter bit fields determine the flexibility of an End Device during association. The A1 pa rameter can be used for an End Device to dynamically set its destination address , PAN ID and/or channel. Coordinator / End Device Setup and Operation To configu re a module to operate as a Coordinator, set the CE (Coordinator Enable) paramet er to 1. Set the CE parameter of End Devices to 0 (default). Coordinator and End Dev ices should con-tain matching firmware versions. NonBeacon (w/ Coordinator) Syst ems In a NonBeacon (w/ Coordinator) system, the Coordinator can be configured to use direct or indirect transmissions. If the SP (Cyclic Sleep Period) parameter is set to 0, the Coordinator will send data immediately. Otherwise, the SP parame ter determines the length 71

of time the Coordinator will retain the data before discarding it. Generally, SP (Cyclic Sleep Period) and ST (Time before Sleep) parameters should be set to ma tch the SP and ST settings of the End Devices. Coordinator Power-up Coordinator power-up is governed by the A2 (Coordinator Association) command. On power-up, t he Coordinator undergoes the following sequence of events: 1. Check A2 parameter - Reassign_PANID Flag: Set (bit 0 = 1) - The Coordinator issues an Active Scan. The Active Scan selects one channel and transmits a Beacon Request command to th e broadcast address (0xFFFF) and broadcast PAN ID (0xFFFF). It then listens on t hat channel for beacons from any Coordinator operating on that channel. The list en time on each channel is determined by the SD (Scan Duration) parameter value. Once the time expires on that channel, the Active Scan selects another channel and again transmits the BeaconRequest as before. This process continues until al l channels have been scanned, or until 5 PANs have been discovered. When the Act ive Scan is complete, the results include a list of PAN IDs and Channels that ar e being used by other PANs. This list is used to assign an unique PAN ID to the new Coordinator. The ID parameter will be retained if it is not found in the Act ive Scan results. Otherwise, the ID (PAN ID) parameter setting will be updated t o a PAN ID that was not detected. Not Set (bit 0 = 0) - The Coordinator retains its ID setting. No Active Scan is performed. For example: If the PAN ID of a Coo rdinator is known, but the operating channel is not; the A1 command on the End D evice should be set to enable the Auto_Associate and Reassign Channel bits. Addition ally, the ID parameter should be set to match the PAN ID of the associated Coord inator. 2. Check A2 parameter - Reassign Channel Flag (bit 1) Set (bit 1 = 1) The Coordinator issues an Energy Scan. The Energy Scan selects one channel and s cans for energy on that channel. The duration of the scan is specified by the SD (Scan Duration) parameter. Once the scan is completed on a channel, the Energy Scan selects the next channel and begins a new scan on that channel. This proces s continues until all channels have been scanned. 72

When the Energy Scan is complete, the results include the maximal energy values detected on each channel. This list is used to determine a channel where the lea st energy was detected. If an Active Scan was performed (Reassign_PANID Flag set ), the channels used by the detected PANs are eliminated as possible channels. T hus, the results of the Energy Scan and the Active Scan (if performed) are used to find the best channel (channel with the least energy that is not used by any detected PAN). Once the best channel has been selected, the CH (Channel) param-e ter value is updated to that channel. Not Set (bit 1 = 0) - The Coordinator reta ins its CH setting. An Energy Scan is not performed. 3. Start Coordinator The Co ordinator starts on the specified channel (CH parameter) and PAN ID (ID paramete r). Note, these may be selected in steps 1 and/or 2 above. The Coordinator will only allow End Devices to associate to it if the A2 parameter Allow Association fl ag is set. Once the Coordinator has successfully started, the Associate LED will blink 1 time per second. (The LED is solid if the Coordinator has not started.) 4. Coordinator Modifications Once a Coordinator has started: Modifying the A2 ( Reassign_Channel or Reassign_PANID bits), ID, CH or MY parameters will cause the Coordinators MAC to reset (The Coordinator RF module (including volatile RAM) is not reset). Changing the A2 Allow Association bit will not reset the Coordinato rs MAC. In a non-beaconing system, End Devices that associated to the Coordinator prior to a MAC reset will have knowledge of the new settings on the Coordinator . Thus, if the Coordinator were to change its ID, CH or MY settings, the End Dev ices would no longer be able to communicate with the non-beacon Coordinator. Onc e a Coordinator has started, the ID, CH, MY or A2 (Reassign_Channel or Reassign_ PANID bits) should not be changed. End Device Power-up End Device power-up is go verned by the A1 (End Device Association) command. On power-up, the End Device u ndergoes the following sequence of events: 1. Check A1 parameter - AutoAssociate Bit Set (bit 2 = 1) - End Device will attempt to associate to a Coordinator. 73

Not Set (bit 2 = 0) - End Device will not attempt to associate to a Coordinator. The End Device will operate as specified by its ID, CH and MY parameters. Assoc iation is considered complete and the Associate LED will blink quickly (5 times per second). When the AutoAssociate bit is not set, the remaining steps (2-3) do not apply. 2. Discover Coordinator (if Auto-Associate Bit Set) The End Device i ssues an Active Scan. The Active Scan selects one channel and transmits a Beacon Request command to the broadcast address (0xFFFF) and broadcast PAN ID (0xFFFF) . It then listens on that channel for beacons from any Coordinator operating on that channel. The listen time on each channel is determined by the SD parameter. Once the time expires on that channel, the Active Scan selects another channel and again transmits the Beacon Request command as before. This process continues until all channels have been scanned, or until 5 PANs have been discovered. Whe n the Active Scan is complete, the results include a list of PAN IDs and Channel s that are being used by detected PANs. The End Device selects a Coordinator to associate with according to the A1 parameter Reassign_PANID and Reassign_Channel fla gs: Reassign_PANID Bit Set (bit 0 = 1)- End Device can associate with a PAN with any ID value. Reassign_PANID Bit Not Set (bit 0 = 0) - End Device will only ass ociate with a PAN whose ID setting matches the ID setting of the End Device. Rea ssign_Channel Bit Set (bit 1 = 1) - End Device can associate with a PAN with any CH value. Reassign_Channel Bit Not Set (bit 1 = 0)- End Device will only associ ate with a PAN whose CH setting matches the CH setting of the End Device. After applying these filters to the discovered Coordinators, if multiple candidate PAN s exist, the End Device will select the PAN whose transmission link quality is t he strongest. If no valid Coordinator is found, the End Device will either go to sleep (as dictated by its SM (Sleep Mode) parameter) or retry Association. Note - An End Device will also disqualify Coordinators if they are not allowing asso ciation (A2 - AllowAssociation bit); or, if the Coordinator is not using the sam e NonBeacon scheme as the End Device. (They must both be programmed with NonBeac on code.) 3. Associate to Valid Coordinator 74

Once a valid Coordinator is found (step 2), the End Device sends an Association Request message to the Coordinator. It then waits for an Association Confirmatio n to be sent from the Coordinator. Once the Confirmation is received, the End De vice is Associated and the Associate LED will blink rapidly (2 times per second) . The LED is solid if the End Device has not associated. 4. End Device Changes o nce an End Device has associated Changing A1, ID or CH parameters will cause the End Device to disassociate and restart the Association procedure. If the End De vice fails to associate, the AI command can give some indication of the failure. 6.8 Zigbee Addressing: Every RF data packet sent over-the-air contains a Source Address and Destination Address field in its header. The RF module conforms to the 802.15.4 specification and supports both short 16-bit addresses and long 64bit addresses. A unique 64-bit IEEE source address is assigned at the factory an d can be read with the SL (Serial Number Low) and SH (Serial Number High) comman ds. Short addressing must be configured manually. A module will use its unique 6 4-bit address as its Source Address if its MY (16-bit Source Address) value is 0x FFFF or 0xFFFE. To send a packet to a specific module using 64-bit addressing: Set Destination Address (DL + DH) to match the Source Address (SL + SH) of the inten ded destination module. To send a packet to a specific module using 16-bit addre ssing: Set DL (Destination Address Low) parameter to equal the MY parameter and set the DH (Destination Address High) parameter to 0. 6.8.1 Unicast Mode By defaul t, the RF module operates in Unicast Mode. Unicast Mode is the only mode that su pports retries. While in this mode, receiving modules send an ACK (acknowledgeme nt) of RF packet reception to the transmitter. If the transmitting module does n ot receive the ACK, it will re-send the packet up to three times or until the AC K is received. Short 16-bit addresses. The module can be configured to use short 16-bit addresses as the Source Address by setting (MY < 0xFFFE). Setting the DH parameter (DH = 0) will configure the Destination Address to be a short 16-bit address (if DL < 0xFFFE). For two modules to communicate using short addressing, the Destination Address of the transmitter module must match the 75

MY parameter of the receiver. The following table shows a sample network configu ration that would enable Unicast Mode communications using short 16-bit addresse s. Table 6.7: Unicast Network Configuration (using 16-bit addressing) Parameter MY(source address) DH(Destination High) DL(Destination Low) Long 64-bit addresses: RF Module 1 0x01 0 0x02 RF Module 2 0x02 0 0x01 The RF modules serial number (SL parameter concatenated to the SH parameter) can be used as a 64-bit source address when the MY (16-bit Source Address) parame-te r is disabled. When the MY parameter is disabled (set MY = 0xFFFF or 0xFFFE), th e modules source address is set to the 64-bit IEEE address stored in the SH and S L parameters. When an End Device associates to a Coordinator, its MY parameter i s set to 0xFFFE to enable 64- bit addressing. The 64-bit address of the module i s stored as SH and SL parameters. To send a packet to a specific module, the Des tination Address (DL + DH) on one module must match the Source Address (SL + SH) of the other. 6.8.2 Broadcast Mode: Any RF module within range will accept a packet that contains a broadcast addres s. When configured to operate in Broadcast Mode, receiving modules do not send A CKs (Acknowledgements) and transmitting modules do not automatically re-send pac kets as is the case in Unicast Mode. To send a broadcast packet to all modules r egardless of 16-bit or 64bit addressing, set the destination addresses of all th e modules as shown below. Sample Network Configuration (All modules in the netwo rk): DL (Destination Low Address) = 0x0000FFFF DH (Destination High Address) = 0 x00000000 (default value) 6.8Modes of Operation The Transceiver operates in five modes .They are 1. Idle Mode 76

2. Receive mode 3. Transmit Mode 4. Sleep Mode 5. Command Mode Fig: 6.7 Different Modes of Operation The operation of Transceiver in each mode is explained below 1. Idle mode When not receiving or transmitting data, the RF module is in Idle Mode. The modu le shifts into the other modes of operation under the following conditions: Tran smit Mode (Serial data is received in the DI Buffer) Receive Mode (Valid RF data is received through the antenna) Sleep Mode (Sleep Mode condition is met) Comma nd Mode (Command Mode Sequence is issued) Transmit Mode 77

RF data packets: When not receiving or transmitting data, the RF module is in Id le Mode. The module shifts into the each transmitted data packet contains a Sour ce Address and Destination Address field. The Source Address matches the address of the transmitting module as specified by the MY (Source Address) parameter (i f MY >= 0xFFFE), the SH (Serial Number High) parameter or the SL (Serial Number Low) parameter. The <Destination Address> field is created from the DH (Destinat ion Address High) and DL (Destination Address Low) parameter values. The Source Address and/or Destination Address fields will either contain a 16-bit short or long 64-bit long address. There are two methods to transmit data. They are 1. Di rect Transmission If the source address matches the destination address then Dat a is transmitted immediately to the Destination Address. A NonBeaconing Coordina tor can be configured to use only Direct Transmission by setting the SP (Cyclic Sleep Period) parameter to 0. Also, a NonBeaconing Coordinator using indirect tran smissions will revert to direct transmission if it knows the destination module is awake. To enable this behavior, the ST (Time before Sleep) value of the Coord inator must be set to match the ST value of the End Device. Once the End Device either transmits data to the Coordinator or polls the Coordinator for data, the Coordinator will use direct transmission for all subsequent data transmissions t o that module address until ST time (or number of beacons) occurs with no activi ty (at which point it will revert to using indirect transmissions for that modul e address). No activity means no transmission or reception of messages with a spec ific address. Global messages will not reset the ST timer. 2. Indirect Transmiss ion A packet is retained for a period of time and is only transmitted after the destination module (Source Address = Destination Address) requests the data. To configure Indirect Transmissions in a PAN (Personal Area Network), the SP (Cycli c Sleep Period) parameter value on the Coordinator must be set to match the long est sleep value of any End Device. The SP parameter represents time in NonBeacon systems and beacons in Beacon-enabled systems. The sleep period value on the Co ordinator determines how long (time or number of 78

beacons) the Coordinator will retain an indirect message before discarding it. I n NonBeacon networks, an End Device must poll the Coordinator once it wakes from Sleep to determine if the Coordinator has an indirect message for it. For Cycli c Sleep Modes, this is done automatically every time the module wakes (after SP time). For Pin Sleep Modes, the A1 (End Device Association) parameter value must be set to enable Coordinator polling on pin wake-up. Alternatively, an End Devi ce can use the FP (Force Poll) command to poll the Coordinator as needed. Indire ct Transmissions can only occur on a Coordinator. Thus, if all nodes in a networ k are End Devices, only Direct Transmissions will occur. Indirect Transmissions are useful to ensure packet delivery to a sleeping node. The Coordinator current ly is able to retain up to 2 indirect messages. CCA (Clear Channel Assessment) Prior to transmitting a packet, a CCA (Clear Channel Assessment) is performed on the channel to determine if the channel is available for transmission. The dete cted energy on the channel is compared with the CA (Clear Channel Assessment) pa rameter value. If the detected energy exceeds the CA parameter value, the packet is not transmitted. Also, a delay is inserted before a transmission takes place . This delay is settable using the RN (Back off Exponent) parameter. If RN is se t to 0, then there is no delay before the first CCA is performed. The RN parameter value is the equivalent of the minBE parameter in the 802.15.4 specification. The transmit sequence follows the 802.15.4 specification. By default, the MM (MAC M ode) parameter = 0. On a CCA failure, the module will attempt to resend the pack et up to two additional times. When in Unicast packets with RR (Retries) = 0, th e module will execute two CCA retires. Broadcast packets always get two CCA reti res. Acknowledgement If the transmission is not a broadcast message, the module will expect to receiv e an acknowledgement from the destination node. If an acknowledgement is not rec eived, the packet will be resent up to 3 more times. If the acknowledgement is n ot received after all transmissions, an ACK failure is recorded. Sleep Mode 79

Sleep Modes enable the RF module to enter states of low-power consumption when n ot in use. In order to enter Sleep Mode, one of the following conditions must be met (in addition to the module having a non-zero SM parameter value): Sleep_RQ (pin 9) is asserted. The module is idle (no data transmission or reception) for the amount of time de fined by the ST (Time before Sleep) parameter. (ST is only active when SM = 4-5). The SM command is central to setting Sleep Mode configurations. By default, Sleep Mo des are disabled (SM = 0) and the module remains in Idle/Receive Mode. When in t his state, the module is constantly ready to respond to serial or RF activity. Higher Voltages Sleep Mode current consumption is highly sensitive to voltage. Voltages above 3. 0V will cause much higher current consumption. Command mode To modify or read RF Module parameters, the module must first enter into Command Mode a state in which incoming characters are interpreted as commands. Two Comm and Mode options are supported: AT Command Mode and API Command Mode. 6.8 AT Command Mode To Enter AT Command Mode: Send the 3-character command sequence +++ and observe guard times before and after the command characters. AT Command Mode Sequence (for transition to Command Mod e): No characters sent for one second [GT (Guard Times) parameter = 0x3E8]. Inpu t three plus characters (+++) within one second [CC (Command Sequence Character) P arameter = 0x2B]. No characters sent for one second [GT (Guard Times) parameter = 0x3E8]. All of the parameter values in the sequence can be modified to reflect user preferences. To Send AT Commands: 80

Fig: 6.8 Syntax for sending AT Commands The preceding example would change the R F module Destination Address (Low) to 0x1F. To store the new value to non-volatile (long term) memory, subsequently send the WR (Write) command. For modified para meter values to persist in the modules registry after a reset, changes must be sa ved to non-volatile memory using the WR (Write) Command. Otherwise, parameters a re restored to previously saved values after the module is reset. System Response When a command is sent to the module, the module will parse and execute the comm and. Upon successful execution of a command, the module returns an OK message. If execution of a command results in an error, the module returns an ERROR message. To Exit AT Command Mode: 1. Send the ATCN (Exit Command Mode) command (followed by a carriage return). 2. If no valid AT Commands are received within the time specified by CT (Command M ode Timeout) Command, the RF module automatically returns to Idle Mode. 6.8.1 AT Commands Description: SH (Serial Number High) Command The SH command is used to read the high 32 bits of the RF module s unique IEEE 64-bit address. The module serial number is set a t the factory and is read-only. AT Command: ATSH Parameter Range: 0 - 0xFFFFFFFF [read-only] Related Commands: SL (Serial Number Low), MY (Source Address). SL ( Serial Number Low) Command 81

The SL command is used to read the low 32 bits of the RF module s unique IEEE 64 bit address. The module serial number is set at the factory and is read-only. AT Command: ATSL Parameter Range: 0 - 0xFFFFFFFF [read-only] Related Commands: SH (Serial Number High), MY (Source Address) DH (Destination Address High) Command The DH command issued to set and read the upper 32 bits of the RF module s 64-bi t destination address. When combined with the DL (Destination Address Low) param eter, it defines the destination address used for transmission. A module will on ly communicate with other modules having the same channel (CH parameter); PAN ID (ID parameter) and destination address (DH + DL parameters). To transmit using a 16-bit address, set the DH parameter to zero and the DL parameter less than 0x FFFF. 0x000000000000FFFF (DL concatenated to DH) is the broadcast address for th e PAN. AT Command: ATDH Parameter Range: 0 - 0xFFFFFFFF Default Parameter Value: 0 Related Commands: DL (Destination Address Low), CH (Channel), ID (PAN VID) DL (Destination Address Low) Command The DL command is used to set and read the lo wer 32 bits of the RF module s 64-bit destination address. When combined with th e DH (Destination Address High) parameter, it defines the destination address us ed for transmission. A module will only communicate with other modules having th e same channel (CH parameter), PAN ID (ID parameter) and destination address (DH + DL parameters). To transmit using a 16-bit address, set the DH parameter to z ero and the DL parameter less than 0xFFFF. 0x000000000000FFFF (DL concatenated t o DH) is the broadcast address for the PAN. 82

AT Command: ATDL Parameter Range: 0 - 0xFFFFFFFF Default Parameter Value: 0 Rela ted Commands: DH (Destination Address High), CH (Channel), ID (PAN VID) DN (Dest ination Node) Command The DN command is used to resolve a NI (Node Identifier) s tring to a physical address. The following events occur upon successful command execution: 1. DL and DH are set to the address of the module with the matching N I (Node Identifier). 2. OK is returned. 3. RF module automatically exits AT Comman d Mode. If there is no response from a modem within 200 msec or a parameter is n ot specified (left blank), the command is terminated and an ERROR message is retur ned. AT Command: ATDN Parameter Range: 20-character ASCII String Minimum Firmwar e Version Required: v1.x80 BD (Interface Data Rate) Command The BD command is us ed to set and read the serial interface data rate used between the RF module and host. This parameter determines the rate at which serial data is sent to the mo dule from the host. Modified interface data rates do not take effect until the C N (Exit AT Command Mode) command is issued and the system returns the OK respo nse. When parameters 0-7 are sent to the module, the respective interface data r ates are used. The RF data rate is not affected by the BD parameter. If the inte rface data rate is set higher than the RF data rate, a flow control configuratio n may need to be implemented. AT Command: ATBD Parameter Range: 0 - 7 (standard rates) 0x80-0x1C200 (non-standard rates) Table: 6.6 Setting Different Baud Rate Parameter Configuration (bps) 83

0 1 2 3 4 5 6 7 Default Parameter Value: 3 CE (Coordinator Enable) Command 1200 2400 4800 9600 19200 38400 57600 115200 The CE command is used to set and read the behavior (End Device vs. Coordinator) of the RF module. AT Command: ATCE Parameter Range: 0 1 Table: 6.7 Configuring the RF Module Parameter 0 1 Default Parameter Value: 0 Minimum Firmware Version Required: v1.x80 Configuration End device Coordinator CH (Channel) Command The CH command is used to set/read the operating channel on which RF connections are made between RF modules. The channel is one of three a ddressing options available to the module. The other options are the PAN ID (ID command) and destination addresses (DL & DH commands). In order for modules to c ommunicate with each other, the modules must share the same channel number. Diff erent channels can be used to prevent modules in one network from listening to t ransmissions of another. Adjacent channel rejection is 23 dB. The module uses ch annel numbers of the 802.15.4 standard. Center Frequency = 2.405 + (CH - 11d) * 5 MHz (d = decimal) 84

AT Command: ATCH Parameter Range: 0x0B - 0x1A (XBee) 0x0C - 0x17 (XBee-PRO) Defa ult Parameter Value: 0x0C (12 decimal) Related Commands: ID (PAN ID), DL (Destin ation Address Low, DH (Destination Address High) ID (Pan ID) Command The ID comm and is used to set and read the PAN (Personal Area Network) ID of the RF module. Only modules with matching PAN IDs can communicate with each other. Unique PAN IDs enable control of which RF packets are received by a module. Setting the ID parameter to 0xFFFF indicates a global transmission for all PANs. It does not in dicate a global receives. AT Command: ATID Parameter Range: 0 - 0xFFFF Default P arameter Value: 0x3332 (13106 decimal) MY (16-bit Source Address) Command The MY command is used to set and read the 16-bit source address of the RF module. By setting MY to 0xFFFF, the reception of RF packets having a 16-bit address is dis abled. The 64-bit address is the modules serial number and is always enabled. AT Command: ATMY Parameter Range: 0 - 0xFFFF Default Parameter Value: 0 Related Com mands: DH (Destination Address High), DL (Destination Address Low), CH (Channel) , ID (PAN ID) NI (Node Identifier) Command The NI command is used to set and rea d a string for identifying a particular node. Rules: Register only accepts print able ASCII data. A string cannot start with a space. 85

A carriage return ends command Command will automatically end when maximum bytes for the string have been entered. This string is returned as part of the ND (No de Discover) command. This identifier is also used with the DN (Destination Node ) command. AT Command: ATNI Parameter Range: 20-character ASCII string Related C ommands: ND (Node Discover), DN (Destination Node) Minimum Firmware Version Requ ired: v1.x80 WR (Write) Command The WR command is used to write configurable par ameters to the RF module s nonvolatile memory. Parameter values remain in the mo dule s memory until overwritten by subsequent use of the WR Command. If changes are made without writing them to non-volatile memory, the module reverts back to previously saved parameters the next time the module is powered-on. AT Command: ATWR VR (Firmware Version) Command The VR command is used to read which firmware vers ion is stored in the module. XBee version numbers will have four significant dig its. The reported number will show three or four numbers and is stated in hexade cimal notation. A version can be reported as "ABC" or "ABCD". Digits ABC are the main release number and D is the revision number from the main release. "D" is not required and if it is not present, a zero is assumed for D. "B" is a variant designator. The following variants exist: "0" = Non-Beacon Enabled 802.15.4 Cod e "1" = Beacon Enabled 802.15.4 Code AT Command: ATVR 86

Parameter Range: 0 - 0xFFFF [read only] AP (API Enable) Command The AP command i s used to enable the RF module to operate using a frame based API instead of usi ng the default Transparent (UART) mode. AT Command: ATAP Parameter Range: 0 2 Ta ble: 6.8 Enabling AP Command Parameter 0 1 2 Default Parameter Value: 0 Minimum Firmware Version Required: v1.x80 EA (ACK Failures) Command The EA command is us ed to reset and read the count of ACK (acknowledgement) failures. This parameter value increment when the module expires its transmission retries without receiv ing an ACK on a packet transmission. This count saturates at its maximum value. Set the parameter to 0 to reset count. AT Command: ATEA Parameter Range: 0 - 0xFFF F Minimum Firmware Version Required: v1.x80 EC (CCA Failures) Command The EC com mand is used to read and reset the count of CCA (Clear Channel Assessment) failu res. These parameter value increments when the RF module does not transmit a pac ket due to the detection of energy that is above the CCA threshold level (set wi th CA command). This count saturates at its maximum value. Set the EC parameter to 0 to reset count. 87 Configuration Disabled (transparent operation ) API enabled API enabled(with esc aped characters)

AT Command: ATEC Parameter Range: 0 - 0xFFFF Related Command: CA (CCA Threshold) Minimum Firmware Version Required: v1.x80 EE (AES Encryption Enable) Command Th e EE command is used to set/read the parameter that disables/enables 128-bit AES encryption. The XBee/XBee-PRO firmware uses the 802.15.4 Default Security proto col and uses AES encryption with a 128-bit key. AES encryption dictates that all modules in the network use the same key and the maximum RF packet size is 95 By tes. When encryption is enabled, the module will always use its 64-bit long addr ess as the source address for RF packets. This does not affect how the MY (Sourc e Address), DH (Destination Address High) and DL (Destination Address Low) param eters work. AT Command: ATEE Parameter Range: 0 - 1 Default Parameter Value: 0 R elated Commands: KY (Encryption Key), AP (API Enable), MM (MAC Mode) Minimum Fir mware Version Required: v1.xA0 VL (Firmware Version - Verbose) The VL command is used to read detailed version information about the RF module. The information includes: Application builds date; MAC, PHY and boot loader versions; and builds dates. AT Command: ATVL Parameter Range: 0 - 0xFF Default Parameter Value: 0x28 (40 decimal) Minimum Firmware Version Required: v1.x80 ND (Node Discover) Comma nd The ND command is used to discover and report all modules on its current oper ating channel (CH parameter) and PAN ID (ID parameter). ND also accepts an NI (N ode 88

Identifier) value as a parameter. In this case, only a module matching the suppl ied identifier will respond. ND uses a 64-bit long address when sending and resp onding to an ND request. The ND command causes a module to transmit a globally a ddressed ND command packet. The amount of time allowed for responses is determin ed by the NT (Node Discover Time) parameter. AT Command: ATND Range: optional 20 -character NI value Related Commands: CH (Channel), ID (Pan ID), MY (Source Addr ess), SH (Serial Number High), SL (Serial Number Low), NI (Node Identifier), NT (Node Discover Time) Minimum Firmware Version Required: v1.x80 AC (Apply Changes ) Command The AC command is used to explicitly apply changes to module parameter values. Applying changes means that the module is re-initialized based on changes made to its parameter values. Once changes are applied, the module immediately operates according to the new parameter values. This behavior is in contrast to issuing the WR (Write) command. The WR command saves parameter values to non-vol atile memory, but the module still operates according to previously saved values until the module is re-booted or the CN (Exit AT Command Mode) command is issue d. AT Command: ATAC Minimum Firmware Version Required: v1.xA0 RE (Restore Defaul ts) Command The RE command is used to restore all configurable parameters to the ir factory default settings. The RE command does not write restored values to no n-volatile (persistent) memory. Issue the WR (Write) command subsequent to issui ng the RE command to save restored parameter values to non-volatile memory. AT C ommand: ATRE 89

HV (Hardware Version) Command The HV command is used to read the hardware versio n of the RF module. AT Command: ATHV Parameter Range: 0 - 0xFFFF [Read-only] Min imum Firmware Version Required: v1.x80 CN (Exit Command Mode) Command The CN command is used to explicitly exit the RF module from AT Command Mode. AT Command: ATCN 6.9 ZIGBEE ARCHITECTURE The IEEE 802.15.4 standard and Zigbee the implementation of a wide range of nd monitoring applications within the he working model of the IEEE 802.15.4 90 wireless network technology are ideal for low cost, low power and reliable control a private home and industrial environment. T and Zigbee is illustrated in Figure 6.9.

Fig: 6.9 Zigbee Architecture In the Zigbee architecture, the PHY layer and MAC l ayer are based on the IEEE 802.15.4 WPAN standard. Zigbee defines the NWK and AP S layers. The software and hardware vendor will provide the software stack with appropriate tools to allow an OEM to create applications, which are added to the APL. The Physical (PHY) layer and Medium Access Control (MAC) layer are based o n the IEEE802.15.4 PAN standard. This includes the actual radio hardware. Above the MAC and PHY are the Network (NWK) and application layers defined by Zigbee. The first two layers, the physical (PHY) and Medium Access Control (MAC) are def ined in the IEEE standard. The other layers that build on the PHY and MAC layers are defined by the Zigbee alliance. The PHY layer contains the RF transceiver a nd access to the other hardware and control mechanisms. The function of the PHY is to activate and deactivate the radio transceiver and other hardware specific services such as access to the channels. The MAC layer is as described by the na me a controlling device for radio medium. It controls access to the physical rad io channel and other services defined by the PHY service. It is also responsible for a reliable transmission system through its services. The services are about channel access and transmission techniques and validation of data packets. The network (NWK) layer is responsible for the network controlling functions. It con trols the mechanism for joining and leaving a network and for creating a network for those devices which have the capability to do so. The NWK layer applies als o security to what is going to be data packets. The NWK layer is responsible for discovery and storing information about the neighbors in the network. Responsib ility for routing between devices and routing of packets to their destination go es to this layer. The application layer (APL) consists of three different blocks which have different functionalities and responsibilities. The application supp ort sub-layer (APS) is responsible for maintaining a table of devices that are c onnected to each other, a binding table. The APS layer provides an interface bet ween the NWK layer and the APL with its set of services. 91

The Zigbee device object (ZDO) is responsible for managing Zigbee devices in the network. This could be discovering new device in the network and define its rol e in the network it also determines the services the new device provides. Possib le device types are those defined in Zigbee standard and they are coordinators, routers and end devices. The Application Frame (AF) contains application objects which can be manufacturer defined application objects. An example of an applica tion object is a power switch. The security service provider (SSP) provides enha nced security options as encryption with 128-bit key transport. PHYSICAL LAYER The physical layer is responsible for the radio hardware device. The standard de fines two hardware Platforms for the IEEE 802.15.4. One describes the 2.4 GHz sp ectrum and one the 868/915 MHz spectrum.The lower band use different modulations technique and lower data rate. Explanations for the different bands are given i n the regulations section. The lower band provides better radio performance when reviewing the frequency band and the antenna performance .specifications in the rest of the report apply only for the 2.4GHz band. Frequency bands: PHY (MHz) F requency Band (MHz) Table: 6.9 Operating Frequency Bands of Zigbee Spreading par ameters Data parameters Chip rate Modulation (k chips/s) 300 600 2000 BPSK BPSK O-QPSK Bit Symbol rate rate (k symbol/s) (kb/s) 20 20 40 250 40 62.5 symbols Bin ary Binary 16-ary Orthogo nal channels 0 1-10 11-26 865/ 915 868-868.6 902-928 2400 24002483.5 Responsibility The layer is responsible for the hardware and can be divided into the following tasks: Activation and deactivation of radio transceiver. Data tra nsmission and reception. 92

Channel frequency selection. Indicator for radio quality within channels and for packets. Channel access assessment technique. Layer service The PHY data service is responsible of transport of MPDU between M AC peer sublayers through the PD-SAP. This is done by data primitives such as PD -DATA request. The PLME is responsible for managing a database of managed object s by the PHY. It is referred to as PHY information base (PIB). The PLME-SAP is r esponsible for management commands between the MAC layer management entity (MLME ) and the PLME. The primitives that are provided are defined for the PLME. They provide for example performing CCA, Energy Detection (ED) measurements or access ing the PIB data base. PHY enumeration descriptions, constants and PIB attribute s are defined in a table in the standard. The maximum PSDU that the PHY shall be able to receive from the MAC layer is 127 octets as described in the introducti on. Turnaround times for TX-to-RX and RX-to-TX shall be a maximum of 12 data sym bol periods. Each symbol is 4 bits which gives a maximum turnaround time of 6 oc tet periods. The spreading of the data decreases the raw data transfer but leads to a much higher reliability in the transmission. Errors in the baseband chip s equence do not mean errors in the raw data. The probability to recognize the cor rect symbol even if bit errors have occurred is high. The O-QPSK modulation used is equivalent to MSK modulation. It utilizes constant amplitude and enables use of relatively nonlinear amplifier designs which means more simple and low cost construction. MAC LAYER The MAC layer is responsible for accessing the physical radio channel through th e PHY layer. It provides services to enable reliable single hop communication lin ks between devices in a network. The services are about channel access and trans mission techniques and validation of data packets. Layer Service 93

The services provided by the MAC layer can be divided into these sub groups: Pro viding a single-hop peer link between MAC entities. Supporting PAN association a nd dissociation. Using CSMA-CA mechanism for channel access. Handling and mainta ining of GTS mechanism. Generate network beacons if device is coordinator. Synch ronization to network beacons. Supporting device security. Layer Structure The structure communication model is similar to the PHY layer. T he MAC layer includes a management entity (MLME) which provides interface to man agement entities on other devices. The MLME is also responsible of maintaining a data base of management objects. The MAC sub-layer provides two services access ed through the data entity and management. The services are provided for the PHY layer and next higher layer. Data services provided by the MAC layer are those for requesting and confirming data for example. Management services in the MAC l ayer is among others association primitives, beacon primitives and channel scann ing primitives. CSMA-CA The CSMA-CA algorithm implements time units called backo ff periods. In slotted CSMA-CA the backoff periods of every device in the networ k are aligned with the super frame boundaries of the coordinator. In the unslott ed CSMA-CA the backoff periods of devices in the network are not related in time to any other device 9in the PAN. The IEEE 802.15.4 MAC sub layer controls the a ccess to the radio channel using the CSMA-CA (Carrier Sense Multiple Access with Collision Avoidance) method, and handles network (dis)association and MAC layer security (AES-128 encryption based). It is also responsible for flow control vi a acknowledgement and retransmission of data packets, frame validation, and netw ork synchronization as well as support to upper layers for robust link operation . The Zigbee wireless technology specifies the network, security, and applicatio n 94

layers upon the IEEE 802.15.4 PHY and MAC layers. The Zigbee Alliance also provi des interoperability and conformance testing specifications. Channel Access Ther e are two types of channel access in the IEEE 802.15.4 defined communication sys tem. They are based on contention which decides if the devices retain their own time slot for communication. The contention based allows the devices to access c hannel in the distributed way using CSMA-CA algorithm. With this contention free method the network coordinator decides about the channel access with the use of Guaranteed Time Slots (GTS) of the channel space. This contention free method i s suitable for latency sensitive devices that require short delay time and no co mpetition of the channel access. Transmission Transmission, reception and acknow ledgements are procedures for sending data, receiving data and for acknowledging that data has been received or sent. Retransmission of data if error occurs if bounded to acknowledgments procedures that are optional. Security The MAC layer is responsible for providing security services when requested by higher layers. The higher layers are responsible for information necessary to provide needed se curity services. Key management, device authentication and freshness protection may be services provided by higher layers but out of the scope for this standard .. The IEEE 802.15.4 supports the following security services: Access control Da ta encryption Frame integrity Sequential freshness The security can be implement ed on both incoming and outgoing frames. Access control provides and maintains a n Access Control List (ACL). The list contains devices that have been selected a nd approved for communicating with. Data encryption security service uses a symm etric cipher to encrypt data for parties who do not have the cryptographic key. In this standard the data encryption may be provided on beacon payloads, command payloads and data payloads. Frame integrity service provides assurance that dat a have not been modified by parties without the cryptographic key and also that data originates from sources with the key. The service may be provided on beacon frames, 95

command frames and data frames. Sequential freshness uses a sequence to protect from frames that are not the original in some manner. NETWORK LAYER The NWK layer is the first Zigbee layer. It is build upon the MAC and PHY layers . The NWK layer provides services for routing and multi-hop communication needed to build different network topologies it is required for correct functionality for underlying layers. It acts as a interface for next higher layer, the applica tion layer. It includes a NWK layer management entity (NLME). The NLME and the N WK layer data entity (NLDE) uses the NLME-SAP and the NLDE-SAP for communicating to other layers. The NLDE provides two kinds of services Generate NWK Protocol Data Unit (NPDU) from next higher layer, APS layer. Deliver NPDU to recipient or route it to the next step towards the destination. The NLME provides the follow ing services: Configuring a new device Starting a network Joining and leaving a network Addressing Neighbour discovery Route discovery Reception control Attribu tes A list of constants is characterizing the NWK layer. A list of attributes is also given and it is used to manage the NWK layer of a device. An attribute is a data entity that represents a physical quantity or a state. The attribute data is sent using commands. Building network 96

The procedures for building networks are build on those defined in the MAC layer . Only coordinators are able to build a network. After that is guaranteed an ED scan is performed followed by an active scan. When data is processed a PAN ident ifier is selected, channel selection are made and a network address is assigned. Joining network Coordinators and routers can permit devices to join the network. The relationship between the device that provides permission and the device tha t wants to join the network is called a parent-child relationship. A parent can directly accept a child and join it to the network with the 64 bit IEEE address. The child retains then a short logical address. When a device wants to join a n etwork first a scan procedure is performed. A suitable parent is searched for fr om the neighbour table. Joining the network is then done by an association reque st. If joining was successful the new device receives a 16 bit short address for communication within the network. The devices are then updating the information in their neighbour tables. Orphaning is the procedure that is performed when a child loose connection to its network or to its parent. The leaving of a network can be done either by request from the child or as a request from the parent to force the child device to leave the network. Every device has an associated dep th. It tells the minimum hops a data frame has to perform through parent links t o reach the coordinator. The coordinator itself has 0 depth and its children hav e 1 depth. The maximum depth of the network is decided by the coordinator. Neigh bour tables shall contain information about devices within a specified transmiss ion range. The information shall be used for different purpose and contains basi c device and network information. It can also be increased with more information . A table entry shall be updated each time a device receives a frame from the ne ighbour. The addressing of joined devices can be assigned in two ways. Either as distributed address assignment mechanism or as higher-layer address assignment mechanism. APL LAYER The application layer is the second of two Zigbee layers. The application layer houses the responsibility for overall device management. It is also responsible for applications and 97

service function within the application layer and to the NWK layer. The applicat ion layer consists of the APS, AF and ZDO. There are two addressing concepts for Zigbee devices. It consists of addressing the specific radio hardware or the ap plication object. They are called node addressing respective endpoint addressing . A node refers to a single radio device. A node could consist of several subuni ts where each subunit has a device description. Each subunit is assigned its own specific endpoint which range from 1 to 240. Each endpoint has a description th at describes for example what it does and which attributes it has. Attributes ar e variables that represent physical quantity or states. In a typical application an attribute could be temperature and endpoints could be sensor applications fo r temperature and humidity. A cluster is identifier of messages that are sent an d are also container for attributes. A Zigbee device would then represent a node that could be an indoors climate report station and another Zigbee device node a controller and communication central for a climate control centre. Application support sub-layer (APS) The APS provides interface between the NWK layer and ap plication layer. The services are offered via the two services, APS Data Entity (APSDE) and APS Management Entity (APSME). The APSDE provides data transmission through its APSDE-SAP and the management entity provides all other services thro ugh APSME-SAP. The APSDE provides these services Generation of APDU-APS layer sp ecific frame are generated Binding-Transmission between matched devices The APSM E provides these services: Interaction with Zigbee Stack Binding-Ability to matc h devices Security-Security relationships with use of keys Transmission If an in direct transmission is sent the originating device shall direct the transmission to the Zigbee coordinator which handles message reflection. The Zigbee coordina tor contains the binding table and shall search for table entry that matches the source address, the cluster identifier or the source endpoint field. The transm ission shall be directed to each of these 98

matched entries. The source address is retained from the NWK layer, the cluster identifier and the source endpoint is included in the frame. The indirect transm ission shall include the source endpoint or destination endpoint field depending on direction with respect to the coordinator. If the transmission is towards th e coordinator for relay it shall contain destination endpoint. If it is directed from coordinator after relay it shall contain the source endpoint. Acknowledgem ent is optional and in indirect addressing the coordinator shall answer acknowle dgement request from originating devices and requesting acknowledgement from dev ices that frames are relayed to. Retransmissions are bound to acknowledgement. W hen acknowledge is enabled retransmission shall be performed if error occurs. Ap plication Framework (AF) The application frame work is containing the applicatio n objects and provides services that the application uses. The applications comm unicate through the APSDE-SAP. The control and management of application frame i s performed by ZDO public interfaces. The primitives is as for the APS sub-layer request, confirm and indication. Endpoints The application framework can house up to 240 application objects. Each one is defined on an endpoint with index fro m 1 to 240, see figure 2.13. Endpoint 0 is reserved and is used for interface to the ZDO and endpoint 255 is reserved for broadcasting of data to all applicatio n objects. ZDO The ZDO is responsible for overall device management and handling of services. It uses its services to implement three different logical Zigbee d evices, coordinator, router and end device. The ZDO is interfacing the managemen t entities of the NWK and the APS sublayer. The ZDO is responsible for assemblin Device and se g data configuration from end points to implement these functions: rvice discovery Security manager Network manager Node manager 99

LATCH The 74LS244 are Octal Buffers and Line Drivers designed to be employed as memory address drivers, clock drivers and bus-oriented transmitters/receivers which pr ovide improved PC board density. The designer has a choice of selected combinati ons of inverting and non inverting outputs, symmetrical, active-low output-contr ol (G) inputs, and complementary output-control (G and G) inputs. These devices feature high fan-out, improved fan-in, and 400-mV noise margin. Hysteresis at In puts to Improve Noise Margins 3-State Outputs Drive Bus Lines or Buffer Memory A ddress Registers Input Clamp Diodes Limit High-Speed Termination Effects Logic and pin connection diagram: Truth table: LANDMINE DETECTOR: === Modern developments === 100

The modern development of the LANDMINE detector began in the 1930s. [[Gerhard Fi sher]] had developed a system of radio direction-finding, which was to be used f or accurate navigation. The system worked extremely well, but Fisher noticed tha t there were anomalies in areas where the terrain contained ore-bearing rocks. H e reasoned that if a radio beam could be distorted by LANDMINE, then it should b e possible to design a machine which would detect LANDMINE using a search coil r esonating at a radio frequency. In 1937 he applied for, and was granted, the fir st patent for a LANDMINE detector. However, it was one [[Lieutenant]] [[Jzef Kosa cki 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]].<ref>"The P olish Contribution to The Ultimate Allied Victory in The Second World War" Tadeu sz Modelski, Worthing, England 1986, Page 221</ref> They were heavy, ran on vacu um tubes, and needed separate battery packs. The design invented by Kosacki was used extensively during the clearance of the German mine fields during the [[Sec ond Battle of El Alamein]] when 500 units were shipped to [[Bernard Montgomery, 1st Viscount Montgomery of Alamein Field Marshal Montgomery]] to clear the minef ields of the retreating Germans, and later used during the [[Allied invasion of Sicily]], the [[Allied invasion of Italy]] and the [[Invasion of Normandy]]. <re f>"The History of Landmines" by Mike Croll published in Great Britain in 1998 by Leo Cooper, Pen & Sword Books Ltd. ISBN 0850522680</ref>As it was a wartime res earch operation to create and refine the design of the detector, the knowledge t hat Stanislaw created the first practical LANDMINE 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 LANDMINE detecting into a hobby. Description This is the circuit diagram of a low cost LANDMINE detector using a single transistor circuit and an old pocket radio..This is nothing but a Colpitt s oscillator working in the medium band frequency and a radio tuned to the same frequency.First the radio and the circuit are placed close.Then the radio is tun ed so that there is no sound from radio.In this condition the radio and the circ uit will be in same frequency and same frequencies beat off to produce no sound. This is the set up.When the LANDMINE detector circuit is placed near to a LANDMI NE object the inductance of its coil changes , and so do the frequency of oscill ations.Now the two frequency will be different , there will be no canceling and radio produces a hissing sound.The LANDMINE is detected. Turck is offering its i nnovative Uprox+sensor line that it believes will set a new standard for LANDMIN E detection. Uprox+sensors are capable of precisely detecting materials such as iron steel, stainless steel, copper, aluminium and brass at extended sensing dis tances without a reduction in the rated sensing distance of the sensor. Uprox+se nsors are claimed to offer unrivalled performance due to a newly patented multic oil system. This multicoil system replaces the wound coil found in conventional ferrite core inductive sensors, resulting in extended sensing distances (up to 2 50% higher) and the flexibility to incorporate this technology in a variety of u nique housing designs. 101

The sensors also feature an integrated pre-damping protection function to reduce the LANDMINE free mounting area in applications. This allows traditionally flus h mounted sensors to be recessed by half a turn for increased mechanical protect ion. Non-flush mounted sensors may be embedded in LANDMINE up to the outer edge of the thread on barrel style sensors and on all four sides of rectangular style sensors, causing only a slight reduction in sensing distance. All Uprox+proximi ty sensors adhere to the present EN50082-2 standard, yet they also exceed the st rict provisions required by EN61000-4-6: an integral part of industry standards by the year 2006 and beyond. This protects against conducted interference from f requency converters, and other sources that produce a high level of EMI. Uprox+s ensors provide a product that incorporates a multitude of sensing requirements; whether for the automotive industry, machine engineering or for transport and ha ndling applications, Uprox+sensors are capable of replacing several conventional proximity sensors. WEBCAM "Webcam" refers to the technology generally; the first part of the term ( "web-") is often replaced with a word describing what can be viewed with the cam era, such as a netcam or streetcam. Webcams are video capturing devices connecte d to computers or computer networks, often using USB or, if they connect to netw orks, Ethernet or Wi-Fi. They are well-known for low manufacturing costs and fle xible applications. Video capture is the process of converting an analog video s ignalsuch as that produced by a video camera or DVD playerto digital form. The res ulting digital data are referred to as a digital video stream, or more often, si mply video stream. This is in contrast with screen casting, in which previously digitized video is captured while displayed on a digital monitor Webcams typical ly include a lens, an image sensor, and some support electronics. Various lenses are available, the most common being a plastic lens that can be screwed in and out to set the camera s focus. Fixed focus lenses, which have no provision for a djustment, are also available. Image sensors can be CMOS or CCD, the former bein g dominant for low-cost cameras, but CCD cameras do not necessarily outperform C MOS-based cameras in the low cost price range. Consumer webcams are usually VGA resolution with a frame rate of 30 frames per second. Higher resolutions, in meg a pixels, are available and higher frame rates are starting to appear. 102

The video capture process involves several processing steps. First the analog vi deo signal is digitized by an analog-to-digital converter to produce a raw, digi tal data stream. In the case of composite video, the luminance and chrominance a re then separated. Next, the chrominance is demodulated to produce color differe nce video data. At this point, the data may be modified so as to adjust brightne ss, contrast, saturation and hue. Finally, the data is transformed by a color sp ace converter to generate data in conformance with any of several color space st andards, such as RGB and YCbCr. Together, these steps constituted video decoding , because they "decode" an analog video format such as NTSC or PAL. Hardware Spe cial electronic circuitry is required to capture video from analog video sources . At the system level this function is typically performed by a dedicated video capture card. Such cards often utilize video decoder integrated circuits to impl ement the video decoding process. Support electronics are present to read the im age from the sensor and transmit it to the host computer. The camera pictured to the right, for example, uses a Sonix SN9C101 to transmit its image over USB. So me cameras - such as mobile phone cameras - use a CMOS sensor with supporting el ectronics. FEATURES: Smallest wireless video & audio camera Wireless transm n and reception High sensitivity Easy installation & operation Easy to conceat L ight weight Low power consumption Small size SPECIFICATIONS: Output frequency: 900MHZ 1200MHZ Output power: 50mW 200mW Power supply: DC +6~12v Distance covered: 10m 103

REGULATED POWER SUPPLY DESCRIPTION A variable regulated power supply, also called a variable bench powe r supply, is one where you can continuously adjust the output voltage to your re quirements. Varying the output of the power supply is the recommended way to tes t a project after having double checked parts placement against circuit drawings and the parts placement guide. This type of regulation is ideal for having a si mple variable bench power supply. Actually this is quite important because one o f the first projects a hobbyist should undertake is the construction of a variab le regulated power supply. While a dedicated supply is quite handy e.g. 5V or 12 V, it s much handier to have a variable supply on hand, especially for testing. Most digital logic circuits and processors need a 5-volt power supply. To use th ese parts we need to build a regulated 5-volt source. Usually you start with an unregulated power supply ranging from 9 volts to 24 volts DC. To make a 5 volt p ower supply, we use a LM7805 voltage regulator IC (Integrated Circuit). The IC i s shown below. The LM7805 is simple to use. You simply connect the positive lead of your unregu lated DC power supply (anything from 9VDC to 24VDC) to the Input pin, connect th e negative lead to the Common pin and then when you turn on the power, you get a 5 volt supply from the Output pin. 104

CIRCUIT FEATURES: Brief description of operation: ives out well regulated +5V ou tput, output current capability of 100 mA Circuit protection: uilt-in overheatin g protection shuts down output when regulator IC gets too hot Circuit complexity : Very simple and easy to build Circuit performance: Very stable +5V output volt age, reliable operation Availability of components: Easy to get, uses only very common basic components Design testing: Based on datasheet example circuit, I ha ve used this circuit succesfully as part of many electronics projects Applicatio ns: Part of electronics devices, small laboratory power supply Power supply volt age: Unreglated DC 8-18V power supply Power supply current: Needed output curren t + 5 mA Component costs: Few dollars for the electronics components + the input transformer cost. 105

CIRCUIT DIAGRAM: Fig : Power Supply Circuit Diagram This 5V dc acts as Vcc to the microcontroller. The excess voltage is dissipated as heat via an Aluminum heat sink attached to the voltage regulator. Bridge Rectifier: A diode bridge is an arrangement of four diodes connected in a bridge circuit as shown below, that provides the same polarity of output voltage for any polarity of 106

the input voltage. When used in its most common application, for conversion of a lternating current (AC) input into direct current (DC) output, it is known as a bridge rectifier. The diagram describes a diode-bridge design known as a full-wa ve rectifier. This design can be used to rectify single phase AC when no transfo rmer center tap is available. A bridge rectifier makes use of four diodes in a b ridge arrangement to achieve full-wave rectification. This is a widely used conf iguration, both with individual diodes wired as shown and with single component bridges where the diode bridge is wired internally. Typical Bridge Rectifier For both positive and negative swings of the transforme r, there is a Forward path through the diode bridge. Both conduction paths cause Current to flow in the same direction through the load resistor accomplishing f ull-wave rectification. While one set of diodes is forward biased, the other set is reverse biased and effectively eliminated from the circuit. Current Flow in the Bridge Rectifier Current in Bridge Rectifier for +ve half cycle 107

Current in Bridge Rectifier for -ve half cycle 9.Software Components: Data Types: U people have already come across the word Data types in C- Language. Here also th e functionality and the meaning of the word is same except a small change in the prefix of their labels. Now we will discuss some of the widely used data types for embedded Cprogramming. Data Types unsigned char signed char unsigned int sig ned int sbit bit sfr Size in Bits 8-bit 8-bit 16-bit 16-bit 1-bit 1-bit 8-bit Da ta Range/Usage 0-255 -128 to +127 0 to 65535 -32,768 to +32,767 SFR bit addressa ble only RAM bit addressable only RAM addresses 80-FFH only Unsigned char: The unsigned char is an 8-bit data type that takes a value in the range of 0-255 (00FFH). It is used in many situations, such as setting a counter value, where t here is no need for signed data we should use the unsigned char instead of the s igned char. Remember that C compilers use the signed char as the default if we d o not put the key word. Signed char: 108

The signed char is an 8-bit data type that uses the most significant bit (D7 of D7-D0) to represent the or + values. As a result, we have only 7 bits for the ma gnitude of the signed number, giving us values from -128 to +127. In situations where + and are needed to represent a given quantity such as temperature, the us e of the signed char data type is a must. Unsigned int: The unsigned int is a 16-bit data type that takes a value in the range of 0 to 6 5535 (0000-FFFFH).It is also used to set counter values of more than 256. We mus t use the int data type unless we have to. Since registers and memory are in 8-b it chunks, the misuse of int variables will result in a larger hex file. To over come this we can use the unsigned char in place of unsigned int. Signed Signed D0) to ude of int: int is a 16-bit data type that uses the most significant bit (D15 of D15represent the or + value. As a result we have only 15 bits for the magnit the number or values from -32,768 to +32,767.

Sbit (single bit): The sbit data type is widely used and designed specifically to access single bit addressable registers. It allows access to the single bits of the SFR registers . (II) I/O PROGRAMMING IN EMBEDDED C: In this topic we look at C- programming of the I/O ports and also both byte and bit I/O programming. Byte size I/O As we know that ports P0-P3 are byte accessible, we use the P0-P3 labels as defined in the header file. Bit addressable I/O programming The I/O po rts of P0-P3 are bit- addressable, so we can access a single bit without disturb ing the rest of the port. We use the sbit data type to access a single bit of P0 -P3.the format is Px^y where x is the port and y is the bit. Accessing SFR addre sses 80-FFH Another way to access the SFR RAM space 80-FFH is to use the sfr dat a type. This is shown in the below example. Both the bit and byte addresses for the P0-P3 ports are given in the table. Notice in the given example that there i s no #include<reg51.h> statement which allows us to access any byte of the SFR R AM space 80-FFH. 109

Single Bit Addresses of Ports H 81H 82H 83H 84H 85H 86H 87H H 91H 92H 93H 94H 95H 96H 97H H A1H A2H A3H A4H A5H A6H A7H H B1H B2H B3H B4H B5H B6H B7H

P0 P0.0 P0.1 P1 P1.0 P1.1 P2 P2.0 P2.1 P3 P3.0 P3.1 Ports Bit D0

P0.2 P0.3 P0.4 P1.2 P1.3 P1.4 P2.2 P2.3 P2.4 P3.2 P3.3 P3.4 D1 D2 D3 D4 D5

P0.5 P0.6 P1.5 P1.6 P2.5 P2.6 P3.5 P3.6 D6 D7

P0.7 P1.7 P2.7 P3.7

Addr Addr Addr Addr

80 90 A0 B0

(III) DATA CONVERTION PROGRAMS IN EMBEDDED C Many micro-controllers have a real time clock (RTC) where the time and date are kept even when the power is off. These time and date are often in packed BCD by RTC. To display them they must be converted to ASCII. So, in this topic we are s howing application of logic and instructions in the conversion of BCD and ASCII. ASCII numbers On ASCII key boards, when the key 0 is activated, 0110000 (30h) is pr ovided to the system. Similarly 31h (0110001) is provided for the key 1, and so on as shown in the table Packed BCD to ASCII conversion The RTC provides the time of day (hour, minutes, seconds) and the date (year, month, day) continuously, re gardless of whether the power is ON or OFF. In the conversion procedure the pack ed BCD is first converted to unpacked BCD. Then it is tagged with 0110000 (30h). ASCII code for Digits 0-9 110

Key 0 1 2 3 4 5 6 7 8 9 ASCII (hex) 30 31 32 33 34 35 36 37 38 39 Binary 011 0000 011 0001 011 0010 011 0011 011 0100 011 0101 011 0110 011 0111 0 11 1000 011 1001 BCD (unpacked) 0000 0000 0000 0001 0000 0010 0000 0011 0000 0100 0000 0101 0000 0110 0000 0111 0000 1000 0000 1001 ASCII to packed BCD conversion To convert ASCII to packed BCD it is first conver ted to unpacked and then combined to make packed BCD. For example 4 and 7 on the keyboard give 34h and 37h respectively the goal is to produce 47h or 0100 0111 wh ich is packed BCD. Key 4 7 ASCII 34 37 unpacked BCD 00000100 00000111 01000111 o r 47h packed BCD Checksum byte in ROM To ensure the integrity of ROM contents, every system must perform the checksum calculation. The process of checksum will detect any corrup tion of the contents of ROM. One of the cause of the ROM corruption is current s urge either when the system is turned on or during operation. To ensure data int egrity in ROM the checksum process uses, what is a checksum byte. There is an ex tra byte that is tagged to the end of the series of data. To calculate the check sum byte of a series of bytes of data, the following steps can be used 1) Add th e bytes together and drop the carries. 2) Take the 2s complement of the total sum . This is the checksum byte , which becomes the last byte of the series 111

Binary (hex) to decimal and ASCII conversion in embedded C: In C-language we use a function call printf which is standard IO library function doing the conversions of data from binary to decimal, or vice versa. But here we are using our own functions for conversions because it occupies much of memory. One of the most commonly used is binary to decimal conversion. In devices such as ADC chips the data is provided to the controller in binary. In order to displ ay binary data we need to convert it to decimal and then to ASCII. Since the hex adecimal format is a convenient way of representing binary data we refer to bina ry data as hex. The binary data 00-FFH converted to decimal will give us 000 to 255. One way to do this is to divide it by 10 and keep the remainder, for exampl e 11111101 or FDH is 253 in decimal. The following is one version of the algorit hm for conversion of hex (binary) to decimal. Quotient FD/0A 19/0A 19 2 INTRODUC TION TO MATLAB Matlab Introduction MATLAB is a high performance language for tec hnical computing .It integrates computation visualization and programming in an easy to use environment Mat lab stands for matrix laboratory. It was written ori ginally to provide easy access to matrix software developed by LINPACK (linear s ystem package) and EISPACK (Eigen system package) projects. MATLAB is therefore built on a foundation of sophisticated matrix software in which the basic elemen t is matrix that does not require pre dimensioning Typical uses of MATLAB 1. Mat h and computation 2. Algorithm development 3. Data acquisition 4. Data analysis ,exploration ands visualization 5. Scientific and engineering graphics The main features of MATLAB 112 Remainder 3(low digit) LSD 5(middle digit) 2(high digit) (MSD)

1. Advance algorithm for high performance numerical computation ,especially in t he Field matrix algebra 2. A large collection of predefined mathematical functio ns and the ability to define ones own functions. 3. Two-and three dimensional gra phics for plotting and displaying data 4. A complete online help system 5. 6. ar eas Powerful, matrix or vector oriented high level programming language for Tool boxes available for solving advanced problems in several application individual applications. MATLAB MATLAB Programming language User written / Built in functions Graphics 2-D graphics 3-D graphics Color and lighting Animation Computation Linear algebra Signal processing Quadrature Etc External interface Interface with C and FORTRAN Programs Tool boxes Signal processing Image processing Control systems Neural Networks Co mmunications Robust control Statistics Features and capabilities of MATLAB 113

The MATLAB System The MATLAB system consists of five main parts: Development Env ironment. This is the set of tools and facilities that help you use MATLAB funct ions and files. Many of these tools are graphical user interfaces. It includes t he MATLAB desktop and Command Window, a command history, an editor and debugger, and browsers for viewing help, the workspace, files, and the search path. The M ATLAB Mathematical Function Library. This is a vast collection of computational algorithms ranging from elementary functions, like sum, sine, cosine, and comple x arithmetic, to more sophisticated functions like matrix inverse, matrix Eigen values, Bessel functions, and fast Fourier transforms. The MATLAB Language. This is a high-level matrix/array language with control flow statements, functions, data structures, input/output, and object-oriented programming features. It allo ws both "programming in the small" to rapidly create quick and dirty throw-away programs, and "programming in the large" to create large and complex application programs. Graphics. MATLAB has extensive facilities for displaying vectors and matrices as graphs, as well as annotating and printing these graphs. It includes high-level functions for two-dimensional and three-dimensional data visualizati on, image processing, animation, and presentation graphics. It also includes low -level functions that allow you to fully customize the appearance of graphics as well as to build complete graphical user interfaces on your MATLAB applications . The MATLAB Application Program Interface (API). This is a library that allows you to write C and Fortran programs that interact with MATLAB. It includes facil ities for calling routines from MATLAB (dynamic linking), calling MATLAB as a co mputational engine, and for reading and writing MAT-files. Starting MATLAB On Wi ndows platforms, start MATLAB by double-clicking the MATLAB shortcut icon on you r Windows desktop. On UNIX platforms, start MATLAB by typing mat lab at the oper ating system prompt. You can customize MATLAB startup. For example, you can chan ge the directory in which MATLAB starts or automatically execute MATLAB statemen ts in a script file named startup.m 114

MATLAB Desktop When you start MATLAB, the MATLAB desktop appears, containing too ls (graphical user interfaces) for managing files, variables, and applications a ssociated with MATLAB. The following illustration shows the default desktop. You can customize the arrangement of tools and documents to suit your needs. For mo re information about the desktop tools . Implementations 1. Arithmetic operations Entering Matrices The best way for you to get started with MATLAB is to learn how to handle matrices. Start MATLAB and follow along with each example. You can enter matrices into MATLAB in several di fferent ways: Enter an explicit list of elements. Load matrices from external da ta files. Generate matrices using built-in functions. Create matrices with your own functions in M-files. Start by entering Drers matrix as a list of its elements . You only have to follow a few basic conventions: Separate the elements of a ro w with blanks or commas. Use a semicolon, to indicate the end of each row. 115

Surround the entire list of elements with square brackets, [ ]. To enter matrix, simply type in the Command Window A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] MATLAB displays the matrix you just entered: A= 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 This matrix matches the numbers in the engraving. Once you have entere d the matrix, it is automatically remembered in the MATLAB workspace. You can re fer to it simply as A. Now that you have A in the workspace, sum, transpose, and diag You are probably already aware that the special properties of a magic squa re have to do with the various ways of summing its elements. If you take the sum along any row or column, or along either of the two main diagonals, you will al ways get the same number. Let us verify that using MATLAB. The first statement t o try is sum(A) MATLAB replies with ans =34 34 34 34 When you do not specify an output variable, MATLAB uses the variable ans, short for answer, to store the re sults of a calculation. You have computed a row vector containing the sums of th e columns of A. Sure enough, each of the columns has the same sum, the magic sum , 34. How about the row sums? MATLAB has a preference for working with the colum ns of a matrix, so one way to get the row sums is to transpose the matrix, compu te the column sums of the transpose, and then transpose the result. For an addit ional way that avoids the double transpose use the dimension argument for the su m function. MATLAB has two transpose operators. The apostrophe operator (e.g., A ) performs a complex conjugate transposition. It flips a matrix about its main diagonal, and also changes the sign of the imaginary component of any complex el ements of the matrix. The apostrophedot operator (e.g., A .), transposes without affecting the sign of complex elements. For matrices containing all real elemen ts, the two operators return the same result. So 116

A produces ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1 and sum(A ) produces a column vector containing the row sums ans = 34 34 34 34 The sum of the elements on the main diagonal is obtained with the sum and the diag functions: diag(A) p roduces ans = 16 10 7 1 and sum(diag(A)) produces ans = 34 The other diagonal, t he so-called anti diagonal, is not so important Mathematically, so MATLAB does n ot have a ready-made function for it. But a function originally intended for use in graphics, fliplr, flips a matrix From left to right: Sum (diag(fliplr(A))) a ns = 117

34 You have verified that the matrix in Drers engraving is indeed magic Square and , in the process, have sampled a few MATLAB matrix operations. Operators Express ions use familiar arithmetic operators and precedence rules. + Addition - Subtra ction * Multiplication / Division \ Left division (described in Matrices and Line ar Algebra in the MATLAB documentation) . ^ Power Complex conjugate transpose ( ) Specify evaluation order Generating Matrices MATLAB provides four functions t hat generate basic matrices. zeros All zeros ones All ones rand Uniformly distri buted random elements randn Normally distributed random elements Here are some e xamples: Z = zeros(2,4) Z= 0000 0000 F = 5*ones(3,3) F= 555 555 555 N = fix(10*r and(1,10)) N= 9264874084 R = randn(4,4) 118

R= 0.6353 0.0860 -0.3210 -1.2316 -0.6014 -2.0046 1.2366 1.0556 0.5512 -0.4931 -0 .6313 -0.1132 -1.0998 0.4620 -2.3252 0.3792 M-Files You can create your own matr ices using M-files, which are text files containing MATLAB code. Use the MATLAB Editor or another text editor to create a file Containing the same statements yo u would type at the MATLAB command Line. Save the file under a name that ends in .m. For example, create a file containing these five lines: A = [... 16.0 3.0 2 .0 13.0 5.0 10.0 11.0 8.0 9.0 6.0 7.0 12.0 4.0 15.0 14.0 1.0 ]; Store the file u nder the name magik.m. Then the statement magik reads the file and creates a var iable, A, containing our example matrix. Graph Components MATLAB displays graphs in a special window known as a figure. To create a graph, you need to define a coordinate system. Therefore every graph is placed within axes, which are contai ned by the figure. The actual visual representation of the data is achieved with graphics objects like lines and surfaces. These objects are drawn within the co ordinate system defined by the axes, which MATLAB automatically creates specific ally to accommodate the range of the data. The actual data is stored as properti es of the graphics objects. 119

Plotting Tools Plotting tools are attached to figures and create an environment for creating Graphs. These tools enable you to do the following: Select from a w ide variety of graph types Change the type of graph that represents a variable S ee and set the properties of graphics objects Annotate graphs with text, arrows, etc. Create and arrange subplots in the figure Drag and drop data into graphs D isplay the plotting tools from the View menu or by clicking the plotting tools i con in the figure toolbar, as shown in the following picture. Editor/Debugger Use the Editor/Debugger to create and debug M-files, which are p rograms you write to run MATLAB functions. The Editor/Debugger provides a graphi cal user interface for text 120

editing, as well as for M-file debugging. To create or edit an M-file use File > New or File > Open, or use the edit function. Results Both the algorithms were applied on different test cases and the following diagr am shows the result in speed and accuracy of both the algorithms 121

. The speed and accuracy of both the algorithms 9.CIRCUIT DESCRIPTION: we can implement a system in which a robot direction can be controlled wirelessl y with respect to the commands given by the user through PC using Zigbee technol ogy The required operating voltage for Microcontroller 89C51 is 5V. Hence the 5V D.C. power supply is needed. This regulated 5V is generated by stepping down th e voltage from 230V to 12V using step down transformer. Now the step downed a.c voltage is being rectified by the Bridge Rectifier using 1N4007 diodes. The rect ified a.c voltage is now filtered using a Capacitor filter. Now the rectified, fil tered D.C. voltage is fed to the Voltage Regulator. This voltage regulator provi des/allows us to have a Regulated constant Voltage which is of +5V. The rectifie d; filtered and regulated voltage is again filtered for ripples using an electro lytic capacitor 100F. Now the output from this section is fed to 40th pin of 89c5 1 microcontroller to supply operating voltage. The microcontroller 89C51 with Pu ll up resistors 122

at Port0 and crystal oscillator of 11.0592 MHz crystal in conjunction with coupl e of 30-33pf capacitors is placed at 18th & 19th pins of 89c51 to make it work ( execute) properly. In this project, there are two sections (transmitter & receiv er) as shown in the block diagrams. The instructions such as Left, Right etc are processed and are given by the person by operating PC. So based upon input of P C the following output will be seen i.e. left or right. In Transmitter Section, the instructions are delivered to Zigbee transceiver from microcontroller which is connected to the PC. This information is processed and is sent to the receive r section via wireless. In Receiver Section, the signals from the transmitter se ction are received by the Zigbee transceiver and send to the controller as input . Controller will process this data and it will control the Robot direction acco rding to the instruction which is given at the transmitter section. Then the Rob ot will move in that particular direction for the given instruction. Similarly c amera directions also controlled. 10.KEIL SOFTWARE: Keil development tools for the 8051 Microcontroller Architecture support every l evel of software developer from the professional applications engineer to the st udent just learning about embedded software development. The industry-standard K eil C Compilers, Macro Assemblers, Debuggers, Real-time Kernels, Single-board Co mputers, and Emulators support all 8051 derivatives and help you get your projec ts completed on schedule. Simulation: The Vision Simulator allows you to debug programs using only your PC using simula tion drivers provided by Keil and various third-party developers. A good simulat ion environment, like Vision, does much more than simply simulate the instruction set of a microcontroller it simulates your entire target system including inter rupts, startup code, on-chip peripherals, external signals, and I/O. This softwa re is used for execution of microcontroller programs. Keil development tools for the MC architecture support every level of software developer from the professi onal applications engineer to the student just learning about embedded 123

software development. The industry-standard keil C compilers, macro assemblers, debuggers, real, time Kernels, Single-board computers and emulators support all microcontroller deriveatives and help you to get more projects completed on sche dule. The keil software development tools are designed to solve the complex Prob lems facing embedded software developers. When starting a new project, simply se lect the microcontroller you the device database and the vision IDE sets all comp iler, assembler, linker, and memory options for you. (PC, Numerous example progr ams are included to help you get started with the The keil Vision debugger accur ately simulates on-chip peripherals CAN, UART, SPI,Interrupts,I/O ports, A/D con verter, D/A converter and PWM modules)of your avr device. Simulation helps you u nderstand h/w configurations and avoids time wasted on setup problems. Additiona lly,with simulation, you can write and test applications before target h/w is av ailable. When you are ready to begin testing your s/w application with target h/ w,use the MON51, MON390, MONADI, or flash MON51 target monitors, the ISD51 In-Sy stem Debugger, or the ULINK USB-JTAG adapter to download and test program code o n your target system. most popular embedded avr devices. 11.SOURCE CODE: 1. Click on the Keil uVision Icon on DeskTop 2. The following fig will appear 124

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 fo lder sited in either C:\ or D:\ 125

6. 7. 8. Then Click on Save button above. Select the component for u r project. i.e. Atme l Click on the + Symbol beside of Atmel 9. Select AT89C52 as shown below 126

10. 11. Then Click on OK The Following fig will appear 12. 13. 14. Then Click either YES or NOmostly NO Now your project is ready to USE Now double clic k on the Target1, you would get another option Source group 1 as shown in next pag e. 127

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 cl icking on its blue boarder. 128

17. 18. Now start writing program in either in C or ASM For a program written in Assembly, t hen 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 129

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

24. 25. If the file contains no error, then press Control+F5 simultaneously. The new win dow is as follows 26. 27. Then Click OK Now Click on the Peripherals from menu bar, and check your required port as show n in fig below 131

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 progra m successfully 132

12.CONCLUSION: The project PC CONTROLLED ed and tested. It has been components used. Presence fully thus contributing to advanced ICs and with the fully implemented.

MILITARY ROBOT USING ZIGBEE has been successfully design developed by integrating features of all the hardware of every module has been reasoned out and placed care the best working of the unit. Secondly, using highly help of growing technology the project has been success

13.FUTURE ENHANCEMENT: This project is to design a robotic system for military applications using zigbe e technology. Here in this project robot is controlled through PC. And to implem ent a system in military areas and also to monitor the locations by using cam wh ich is connected to robot. And also we can implement a system in which a robot d irection can be controlled wirelessly with respect to the commands given by the user through PC using Zigbee technology. 14.BIBLIOGRAPHY: The 8051 Micro controller and Embedded Systems -Muhammad Ali Mazidi Janice Gilli spie Mazidi The 8051 Micro controller Architecture, Programming & Applications Kenneth J.Ayala Fundamentals Of Micro processors and Micro computers -B.Ram Micr o processor Architecture, Programming & Applications -Ramesh S.Gaonkar Electroni c Components -D.V.Prasad Wireless Communications - Theodore S. Rappaport Referen ces on the Web: www.geoci 133