• Save
Unmanned Aerial Vehicle
Upcoming SlideShare
Loading in...5

Unmanned Aerial Vehicle



Intro to Commercial Unmanned Aerial Vehicles/Systems. Partial Free Code :)

Intro to Commercial Unmanned Aerial Vehicles/Systems. Partial Free Code :)



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Unmanned Aerial Vehicle Unmanned Aerial Vehicle Document Transcript

    • Unmanned Aerial VehicleArab Academy for Science and Technology and Maritime Transport College of Engineering and Technology Department of Computer Engineering UNMANNED AERIAL VEHICLE (UAV) Presented by: Alexander Mohamed Osman Riyad Ahmed El-laithy Ruyyan Ahmed El-laithy Peter Raouf Zaky Supervised by: Dr. Ibrahim Imam ((July 2007)) Page 1
    • Unmanned Aerial Vehicle ACKNOWLEDGEMENTS After thanking God the Merciful we would like to send our thanks to the followingpeople: Firstly we would like to thank Dr. Ibrahim Imam for proposing the idea of anUnmanned Aerial Vehicle and for accepting us to carry on that project. Secondly we would like to thank Dr. Atallah Hashad for giving us a helping handwhenever we needed one and for providing us with solutions for all the challenges wefaced. We would like to thank Dr. Hassan Ibrahim for providing us with help with theelectrical problems we faced in our circuits. We would also like to thank Dr. Gamal Selim for his encouragement, assistance andunderstanding. We would like to thank Dr. Yasser Galal for answering some questions we hadabout DC motors. We would also like to thank Eng. Ahmed Akl, Eng. Renad Kamal, Muhab Bahgat,Ruyhan El-Laithy, Fady Mounier, Beshoy Helmy, Todd Elliot, and Sparkfun Electronicsfor supporting us and/or making this possible. Last but not least we would like to thank our parents & families for their love,support, and understanding. Page 2
    • Unmanned Aerial Vehicle ABSTRACT Gathering information from locations which are inhabitable, hostile, or difficult toreach is a crucial aspect for learning new information about unmarked territories andactivities and aids in human technological advancement. This project is concerned withdeveloping an agent for gathering visual information by holding a stationary position orpursuing a dynamic target. The agent is a quadrotor VTOL (Vertical Take Off andLanding) aircraft. This agent should have the capability to hover, fly and follow targets. Itshould receive and transmit data wirelessly into a base station. It should move through apredefined plan using a GPS receiver. It should also balance itself in the air through agyrometer and an accelerometer. In addition it would utilize four ultrasonic sensors forobstacle avoidance and an extra one for landing assistance. The agent would also utilize awireless camera to transmit a bird s eye view to the base station. Page 3
    • Unmanned Aerial Vehicle TABLE OF CONTENTS1. INTRODUCTION .......................72. CONCEPTUAL DESIGN & PHYSICAL ASSEMBLY .. 123. ANALYSIS, COMPONENT-LEVEL DESIGN & SELECTION .18 3.1 Major Components ..18 3.2 PCB Design .. .......25 3.2.1 Interface Boards ...27 GPS interface board .27 Accelerometer / Gyrometer interface board ................28 RF Interface boards 24-G .. ............28 3.2.2 Motor Driver 29 3.2.3 The Brain.. ...314. CONTROL 33 4.1 Introduction .........33 4.2 SPI communication .35 4.3 Main PIC Implementation ................38 4.3.1 Pulse Width Modulation (Motors) ...38 4.3.2 ADC Operation ............43 Ultrasonic Sensors 50 Gyrometer .. ...52 Accelerometer . ..52 4.4 Secondary PIC Implementation ......55 4.4.1 GPS System .55 4.4.2 RF Transceiver .66 4.5 RC Unit ......75 Page 4
    • Unmanned Aerial Vehicle5. TESTING TROUBLESHOOTING AND REDESIGN 78 5.1 Testing ..78 5.1.1 LED Testing ..78 Accelerometer Testing ..78 Gyrometer Testing 78 SPI Testing 79 RC unit testing ..................79 5.1.2 LCD Testing ..80 Ultrasonic testing . ..81 Accelerometer Testing . ..81 RC unit Testing . ................82 GPS Testing . .83 5.1.3 RF Testing . . .83 Ultrasonic Testing . 83 Gyro Testing . 83 RC Unit . 85 5.2 Previous Chassis designs . ...88 5.3 RF Drivers . .....90 5.3.1 Laipac RF TX/RX ...90 5.4 Configuration 1 ......92 5.5 Configuration 2 ..96 5.6 Brain #3 .....99 5.7 Correcting Gyro Output 1006. FUTURE IMPLEMENTATIONS ..1027. CONCLUSION .......103 Page 5
    • Unmanned Aerial Vehicle INTRODUCTION The rapid development of micro-processor technology and the continuous growth ofintegration density of electronical and mechatronical components yields a significant costreduction of high tech products. Driven by this development it becomes feasible to embedinformation processing and communicating devices in all sorts of appliances, toys,production facilities, communication systems, traffic and transport systems etc. With this integration and the aid of global positioning systems, there has been asurge of development in Unmanned Vehicles (UV). The main benefits of UV s are thatthey do not require human control and thus can be reduced in size and cost. They also limithuman error in several aspects, and reduce if not eliminate human endangerment.Unmanned vehicles are developed for use in air, over land and under water by both privateand government agencies. Several unmanned systems exist such as AutonomousUnderwater Vehicles (AUV), Unmanned Ground Vehicle (UGV), and Unmanned CombatVehicles (UCV). NASA deploys USVs (Unmanned Space Vehicles) on rock gatheringmissions from the Moon and Mars. The military advanced UAVs and renamed them toUAVS (Unmanned Aerial Vehicle Systems) and are used in flight combat. Government search and rescue departments find the UAVs helpful in inhabitable orhazardous terrain such as earthquakes, floods or volcanoes, where no human lives have tobe risked. Institutions which have onsite geologists use UAVs for uncovering terrain androck identification, without having to deploy a whole crew working outside. Departmentsof transportation can use this device to cover footage of inaccessible situations such asdead-lock traffic jams or multiple car-crashes. Government law enforcement andintelligence agencies can specifically find this device useful for reconnaissance and targetpursuance, where the UAV provides the advantages of cheap costs, stealth and adiminished human risk factor. The Unmanned Aerial Vehicle project has been an ongoing attempt to produce areliable autonomous hovering or flying vehicle. The project designed and implemented afour-rotor hovering aerial vehicle. The advantages of a hovering vehicle over a fixed-wing Page 7
    • Unmanned Aerial Vehicleflying vehicle include less complexity in design, minimal space for take-off and landing(vertical take-off and landing (VTOL)), indoor flight, maneuverability in obstacle heavyenvironments and of course the eye-catching ability of being able to maintain a staticposition in mid-air. The advantage of quadrotors over helicopters is that they do not require mechanicallinkages to vary rotor angle of attack as they spin, this simplifies design and control. Theuse of four rotors allows each individual rotor to have a smaller diameter than theequivalent helicopter rotor, for a given vehicle size, allowing them to store less kineticenergy during flight. These smaller propellers reduce the damage caused should the rotorshit any objects, this also makes the vehicles safer to interact with in close proximity. The first RC application of a 4-rotor vehicle was the Roswell Flyer made by Area51technologies. Now there are several commercially available quadrotor aerial vehicles, to lista few, Atair aerospace quadcopter , Hammacher Schlemmer four rotor UFO , KeyenceEngager and gyrosaucer and the DraganFlyer V Ti . The team s design was inspired bythe DraganFlyer V, made by Draganfly Innovations Inc. where the four motors and propsare laid at the ends of an X Chassis, and in the center lay the majority of the circuit boardsand microprocessor dubbed by DraganFlyer Inc. as The Brain . (See figure below) Page 8
    • Unmanned Aerial VehicleSystem Block Diagram A general control scheme can be seen in the diagram above. The controller block iscomposed of two communicating MCU s (MicroController Units). The main MCU doesmost of the calculations and decision making. The main MCU also receives inputs from theproximity sensors and stability sensors, while the secondary MCU is responsible forcommunicating with a GPS receiver for positioning and an RF module for wirelesscommunication. Both MCU s then drive the outputs for the four motors together. The stability sensors block consists of a 3-axis Gyrometer for angular velocitymeasurement and a 3-axis accelerometer for measuring acceleration. The proximity sensorsblock consists of 5 ultrasonic sensors placed around the vehicle and under it, for obstacleavoidance and assisted landing. The GPS receiver block consists of a GPS module that provides position, velocity,heading and altitude readings. The RF transceiver block consists of a 2.4GHz RF Modulethat communicates bi-directionally with a remote control unit for sending and receivingdata. Page 9
    • Unmanned Aerial Vehicle The Motor block consists of 4 high powered brushed motors with a gear ratio of5.33:1 and 10x4.5 propellers. Both of these features provide a high thrust vehicle (Asopposed to high speed). These motors are controlled through switching transistor circuitsusing PWM (Pulse Width Modulation). The UAV works in three different modes, in the simplest mode a land based PCsends out signals through an RF transceiver in order to steer the UAV in differentdirections. In the second mode a land based PC receives images from an onboard camera,then a pattern recognition system identifies a target object and sends signals to the UAVthrough the RF transceiver to steer it toward the desired object. If the object is not found theUAV rises in altitude quickly in order to find the object and re-track it. The third mode usesan onboard GPS that gives the current position of the UAV and it compares that to its targetdestination, and steers to its target destination then comes back to its initial point. In allmodes an accelerometer and gyrometer are used to provide stability, and ultrasonic sensorsare used to measure height and avoid obstacles and in turn to steer the UAV away fromthem. Because of the ambitious nature of the project, the team decided to build the UAVfrom ground up. Development of our 4-rotor vehicle can be divided into four majorbranches.1. Conceptual Design and Physical Assembly.2. Analysis, component-level design & selection.3. Control.4. Testing, Troubleshooting & Redesign. Although these four stages overlapped and interfered with one another they can bediscussed independently, without much referencing to other sections. Page 10
    • Unmanned Aerial Vehicle CONCEPTUAL DESIGN & PHYSICAL ASSEMBLY The conceptual design as stated previously was inspired by the DraganFlyer, andthe team s first step was to identify the design goals. These were the fundamentalrequirements the team decided upon: 1. Ability to hover, in the sense of generating enough thrust and have enough control in order to maintain a mid-air static position. 2. Maneuverability in all directions of a three-dimensional plane. 3. Sufficient endurance of no less than 10-15 minutes. 4. A very light-weight body, including a battery with the highest power to weight ratio we could find since the battery is the heaviest single component of the vehicle. 5. High residual thrust to hover thrust ratio, an acrobatic vehicle was desirable for ability to demonstrate controllability and to perform difficult flight maneuvers. 6. Minimal size & complexity. The team decided to stick very close to traditional designs of 4-rotor vehicles, wherefour electric motors are placed on the corners of a rectangle, and drive four counter-rotatingpropellers. These propellers would produce sufficient thrust for take-off, and according totheir different allocated power distributed on the four motors would providemaneuverability. Any propeller spinning produces a torque on the body it is attached to. Forstability in flight the total resulting differential torque on the body should be zero. This isdemonstrated very clearly in helicopters. The main rotor on the roof of the helicopterproduces a large yaw torque on the body which is countered by the tail rotor on the rear ofthe plane. Assuming the main rotor is on a constant rpm, the difference in power to the rearpropeller moves the helicopter around the z-axis. Page 11
    • Unmanned Aerial Vehicle The proper rotation of the propellers, goes such as any two adjacent propellersrotate in opposite directions, and any two diagonal propellers rotate in the same direction.The sum of rotations of any two diagonal propellers should equal the sum of the remainingtwo diagonal propellers. This makes the total differential torque on the body about the z-axis zero. The figure below demonstrates the prop rotation direction. At hover mode, all four propellers would be producing the same amount of torqueresulting in zero-net force on the vehicle about any-axis once gravity is taken into account.To make the vehicle increase or decrease in altitude, the speed on all four propellers areincreased or decreased respectively. In order to move the vehicle in any direction of the xor y axis, two propellers adjacent propellers are increased in thrust, this causes the vehicleto pitch or roll in the desired direction, since the sum of the any two diagonal rotors is stillthe same as their other diagonal pair, this prevents the vehicle from yawing in any directionother than the desired course. Assuming the vehicle is in hover mode the following tableyields a summary of the vehicle control scheme. Use the previous figure for propellerreference. Page 12
    • Unmanned Aerial Vehicle Propeller 1 Propeller 2 Propeller 3 Propeller 4 Z+ (Up) + + + + Z- (Down) - - - - X+ (Left) + 0 0 + X- (Right) 0 + + 0 Y+ (Forward) + + 0 0 Y- (Backward) 0 0 + + As stated earlier, a lightweight body was a must in order to achieve maximum thrustfor ease of flight and acrobatic maneuvers. For the chassis of the plane carbon-fiber wasused, a very stiff and lightweight material, with a variety of practical uses commonly usedin racecars and RC planes for their unique characteristics. To save even more weight weused the X-chassis design, where four motors would be placed on every end of the X-chassis. This would also give a better chance for the high pressure to accumulate andincrease under the blade of the propellers to give higher lift than in a rectangular design. Itwould also reduce the overall air resistance. The arms of the X-chassis were made fromhollow carbon-fiber tubes, and at the end of the tubes the motor mounts were placed. Theywere welded together using a common adhesive known to the RC world as Epoxy . On the bottom of the X-chassis the battery was mounted, keeping the battery on alower point would lower the center of gravity of the vehicle giving the vehicle smootherpitching and rolling. On the four battery sides four ultrasonic sensors would be placed forobstacle avoidance. On the bottom of the battery the fifth ultrasonic sensor was placed todetermine height, along with the wireless camera placed for surveillance purposes, video orimage capturing. On the top of the X-chassis the UAV brain board was placed. It carries theaccelerometer, gyrometer, RF Transceiver, GPS, motor controllers, ultrasonic sensorsconnections, and of course the Microcontrollers. The following figure below displays thechassis. Page 13
    • Unmanned Aerial Vehicle After going through the design and experimentation of three different prototypes(found in 5.2 Previous Chassis designs). One of the most difficult tasks for us, thatabsorbed most of our time was coming up with the chassis that can have completelyreduced air resistance, maximized technical output power when compared to theoreticalpower of the DC Brushed Motors involved, uniform density, and as extremely lightweightas possible with all the components that we have had to add on the UAV. The net weight onthe UAV including all added components added up 990g when measured on the scale,which is almost 1 Kg. The theoretical output power given to us by the DC Brushed Motorsadded to up to a maximum thrust of 390 grams per motor. (See APPENDIX C) Since wehave 4 motors on the UAV, the complete output power given by those motors is 1560grams (1.56Kg). Technically, the team managed to output only around 350 grams permotor, adding up to 1400 grams (1.40Kg) of thrust. The efficiency of our design brought us89.74% of that power. The loss in power comes up to 10.26% due to friction forces, andminimized air resistance. It is made mostly out of lightweight Carbon Fiber and Balsa Wood for the base ofthe electrical circuit. The total weight of the chassis without all the components comes to 43grams. A CAD model was designed, shown in the following figures. An isometric view isshown below, and the dimensions of the chassis design are shown in the next few pages. Page 14
    • Unmanned Aerial VehicleTop View:Front View:Right Side View: Page 15
    • Unmanned Aerial VehicleCalculations:Motor Force: Max OutputTheoretical/Ideal = 390 grams/Motor Max OutputTechnical = 350 grams/MotorTherefore, the Total Motor Output of 4 Motors at Full Power: Max Output4Motors = 1400 grams/4 Motors Maximum Payload = 1400 990 = 410 gramsHence, Max Output in Newtons = 1400 x 9.807 = 13.730 Newtons Max Output per Motor = 13.730/4 = 3.432 NewtonsNet Force:Therefore, Lift of Chassis at Full Power and when Differential Torque = 0. Chassis mass = 990 grams = 0.99 Kg Chassis weight = 0.99 Kg x 9.807 m/s2 = 9.709N Lift = 13.730 9.709 = 4.021 NewtonsAcceleration:Net Force = Lift - Gravity = ma mg4.021 = 13.730 9.7090.99a = 1.4(9.807) 0.99(9.807)a = (0.41(9.807)) / 0.99acceleration = 4.061m/s2Therefore, the Power to Weight Ratio: 1.5 : 1Therefore, Lateral Thrust beyond Hover thrust = (4.061m/s2) / (9.807m/s2) = 0.4141g Page 16
    • Unmanned Aerial VehicleTorque: = Acceleration / Distance to Center = 4.061 m/s2 / 0.14m = 29.007 rad/sec2 = mass * radius2 * (angular velocity) = (0.495) x (0.14) 2 (29.007); where (0.99/2 Motors = 0.495 grams, since it takes 2 motors for the UAV to move front, back, left or right). = 0.2814 Newtons MAX = 4.061 x 0.14 = 0.56854 Newtons A picture of the UAV with complete physical assembly can be seen below in thefollowing figure. Page 17
    • Unmanned Aerial VehicleANALYSIS, COMPONENT-LEVEL DESIGN & SELECTION3.1 Major Components : The selection of the motors were brushed motors the GWS EPS-350C with agearing ratio of 5.33:1, which peak out at 8.0V and 8.0A, each of these weigh 63g and areprojected to deliver 15.37oz (435.73g) of thrust at peak power. Four of these motors areused, with one on each end of the X -chassis. A figure is placed below. Counter-rotating propellers were selected as our default propellers, which are a mustin any quadrotor plane, because motors do not turn in the same direction. We selected10*4.5 propellers which are large considered for our motor. Larger propellers are moresuitable for high thrust application, and smaller rotors are more suitable for high velocityand aerodynamic capabilities. Our choice was the EPP1045 propeller. A figure of thepropeller is placed below. Page 18
    • Unmanned Aerial Vehicle Heat syncs were also used to cool down the motors to increase durability andefficiency as well as to dissipate the heat created by the motors for a longer, more durablelife. The team selected EHS300 an aluminum, multi-fin heat sync for good heat dissipationand proper venting respectively. The heat sync has two large fins and 24 smaller fins. Afigure of the heat sync is placed below. We needed a battery source that can provide more than 32A continuously,considering each motor can consume 8A, the battery of choice was a Lithium-polymerThunder Power TP8000-2S4P two-cell 7.4V, 8AH battery. It can work continuously at 12C(96A), and can burst at 18C (144A) which is more than sufficient to have all motorsworking at full thrust. With a weight of 320 grams and dimensions of 128*50*29mm it hada high power to weight ratio and size relative to its competitors. It would also give us abouta good 15 minutes of airtime if the UAV is flying at full power. A figure of the battery isplaced below. Page 19
    • Unmanned Aerial Vehicle A compatible charger the Astro-flight 109D was selected. Charging rates from50mA - 8A. Lithium polymer batteries can charge at a maximum of 1C of their rating, sothis charger can charge the battery in the fastest possible time which is 1 hour, for quickpractical testing. The battery is two cells, any battery with more than one cell requires abalancer, so a blinky battery balancer was used which balances the cells before, after andduring recharge. A wattmeter was also required to measure the voltage and current of thebattery before and after recharge. A powerful and bulky power supply is required tocontinuously deliver such current to the charger. The astro-flight power supply was used,with an input of 110V/220V and an output of 13.5V, it delivers 12.5A. Figures of thecharger (top left), blinky battery balancer (top right), wattmeter (bottom left), and powersupply (bottom right) are placed below. Page 20
    • Unmanned Aerial Vehicle The accelerometer used was the triple-axis ADXL-330. Works at 3.3V logic, andconsumes 0.32mA, it has three outputs for x, y and z axes. Minimum full scale range is±3g, and a sensitivity of 300mV/g. The gyrometer used is the IDG-300 which also works at3.0V logic and has a full scale range of 500°/sec, and consumes 9.5mA, but has only twooutputs, x and y. Because of this the team had to place two of these IC s onboard, to getangular velocity about all three axes. Pictures of the accelerometer and gyrometer aredisplayed below from left to right. The IMU five degrees of freedom is an IMU (Inertia Measurement Unit) thatcombines the IDG300 gyrometer and an ADXL330 accelerometer. This unit measures xand y angular velocity and x, y, z accelerometer outputs, hence the name 5 degrees offreedom . Its advantages over two separate units are firstly that the x and y outputs of bothhave identical headings, and you only have one VCC and one GND connection.Disadvantages are if this IC for any reason becomes defective you lose two IC s. A figureof this IC is displayed below. Page 21
    • Unmanned Aerial Vehicle Ultrasonic sensors used were the Max sonar LV-EZ1 which work at 5.0V logic andhave a maximum range of 255in (6.45m), which measures in increments of an inch, theyhave analog, digital and pulse width modulated outputs. It consumes 2mA. Five of these areplaced onboard, four facing x and y axes, in order to detect obstacles around the vehicle,and one on the bottom of the battery facing downwards to detect height and aid in landing.We could not rely on the altitude reading of the GPS system for height because there is anerror tolerance of ±5m, this could result in hazardous landings. The extra ultrasonic sensoron the bottom would virtually eliminate that error because its resolution is relatively quitehigh. For communication with ground, radio frequency IC s are used. The LaipacTRF2.4-G transceiver was used. It operates at a high frequency, 2.4GHz. Data ratetransmission can work at either 250kbps or 1Mbps. It works at 3.0V logic consumes10.5mA in TX mode and 18.5mA in RX mode. Maximum range is 280m. Each unit cansend and receive data interchangeably. One of the transceivers is placed onboard, and theother is connected to a land-based PC, they send and receive data to and from each other. Page 22
    • Unmanned Aerial Vehicle For unmanned guidance to different destinations a GPS system, the EM-406 wasused. Readings of latitude, longitude and altitude obtained serially are used to triangulatethe position of the IC. Power input is rated between 4.5V-6.5V and power consumption is70mA, operating frequency is at 1.58GHz. A figure of the GPS is placed below.jhnjh For the surveillance system the WS-309AS system was used, the package comeswith 1.2GHz camera with a resolution of 628*582 and a horizontal definition of 380 lines.The camera works at 9.0V, and consumes 85mA. A simple 9V battery operates the camera.The package also comes with a receiver with audio out and video out. Linear transmissiondistance ranges from 50m-100m. A picture of the camera and components are placedbelow. Page 23
    • Unmanned Aerial Vehicle The selected PIC programmer was the Olimex PIC-MCP-USB programmer. It is alow cost PICSTART alternative, is MPLAB compatible and thus does not require a RS232port. In addition it has an ICSP (In Circuit Serial Programming) connector (ICSPprogramming explained in APPENDIX E). A figure of the programmer is displayed below. Page 24
    • Unmanned Aerial Vehicle3.2 PCB Design Required components for designing and etching a PCB are acetone, a laser printer,glossy paper, a clothing iron, acid and a steel sponge. Firstly the surface of the brass boardis scrubbed with a steel sponge to remove any impurities and any oxidized brass. It is thencleaned thoroughly with cotton drained in acetone. The team used the circuit designingprogram called EAGLE 4.16r1 . Any circuit is printed on glossy paper, the printed glossypaper is then well folded around the board to prevent any slip during ironing, then ironedon the brass board. Ironing continues until the circuit becomes visible from the other side ofthe printed glossy paper, or preferably when the white paper takes a yellowish/brownishcolor indicating a slight burn. (Caution should be taken during ironing, if the brass boardbecomes too hot, the brass actually deforms). After ironing, the paper should be removedleaving the toner ink on the brass board. The brass board is then placed in the acid and leftuntil all brass surrounding the printed circuit is dissolved. After removing from acid andrinsing in water, a steel sponge is gently scrubbed on the toner ink to leave the brass traceunder the toner ink while removing the ink. Holes are drilled into the circuit board in theappropriate places where components are to be placed. After drilling is complete,components are welded onto the board using solder and a soldering iron. All circuits usedfor this project were designed in this manner. Pictures below (left to right) display thisprocedure. Before these boards were actually designed they were tested on bread boards first inorder to assure everything is working in order, because making an incorrect PCB meansmuch wasted time and raw materials. More of this can be referenced in Section 7, Testingtroubleshooting and redesign. Page 25
    • Unmanned Aerial Vehicle Page 26
    • Unmanned Aerial Vehicle3.2.1 Interface Boards Learning from previous errors we found it would be more convenient to createinterface boards for individual IC s rather than integrate them into one large circuit. (Muchthe way a desktop motherboard uses PCI cards instead of making one large board.) This isbecause if any errors occur in the design, or redesigning is desired, the individual IC swouldn t need to be removed. Frequently exposing IC s to strong heat when welding candamage these components. GPS Interface Board In his board the GPS cable is welded onto the left row of pins. The descending orderof these pins is; not used, GND, TX, RX, VIN, & GND, again. The first pin is ignored. Thesecond and last pins (both GND) connect to the right side second pin. The third pin TXconnects to the fourth pin on the right. The 4th pin on the left is RX that connects to thethird pin on the right. Page 27
    • Unmanned Aerial Vehicle3.2.1.2 Accelerometer / Gyrometer Interface BoardThis follows the same method as the GPS interface board. The E$1 row is the yaw gyro,E$2 row is the roll/pitch gyro. E$3 row is the three axis accelerometer. E$4 row is the pinheaders that connect onto the main board. RF boardsThe TRW-24G is a very sensitive component therefore we designed this interface boardwith a TRW-24G socket for plug and play action onto the board. Page 28
    • Unmanned Aerial Vehicle3.2.2 Motor Drivers : Designing a suitable motor controller circuit was a challenging task, especially due tothe lack of components here in Egypt. The controlled motors could take up to 64 Amperebursts for a startup current and up to 8 Amperes as a continuous current. In order to achievemaximum power we needed to cause a minimal voltage drop in our circuit. We came upwith the following design objectives:- Switching speed of up to 2KHz (for PWM control)- Minimum Vce drop possible for more powerful motors- High current Ic- Low current Ib Unfortunately the transistors fitting this description could not be found here inEgypt, but we found a transistor 2SD1062. It is capable of running a current of up to 15Aand Vce of as low as 0.3V, but it needed a larger current for Ib than a PIC could provide,therefore we added a TIP120 transistor as an interface between the PIC and the 2SD1062.Since Vce of the 2SD1062 was a function of the Ic current we put 2 transistors in parallel todrop the Vce as low as possible while at the same time assuring that it has enough capacityto pass through the required current for the motor. A main feature of this circuit is the PC817 optocoupler, an IC that interfacesbetween the PIC circuit and the motor circuit. Isolating these circuits was necessarybecause combining high current components with low current ones can damage the lowcurrent components. The optocoupler in the following diagram is labeled as 2. The leftside of the optocoupler is connected to the PIC circuit and the right side is connected to themotor circuit. The first rows of pins in order are GND (PIC circuit), Vcc (PIC circuit), GND(Motor circuit) and Vcc (Motor circuit). Vcc from PIC (PWM output) circuit goes through a1.5K resistor through optocouplers where the phototransistor is activated and returns tothe PIC ground. The signal in turn goes through the base of the TIP120 turning it on. Theemitter of the TIP120 connects to the base of the 2SD1062 transistors, whose collectors are Page 29
    • Unmanned Aerial Vehicleconnected to the motor and the motor is connected to the Li-Poly battery. A circuitschematic is shown below. Resistors were placed to produce desired voltage drops. In the final motor driver design, the optocoupler was removed from the motor driverand put on the main brain. This was done in order to have smaller motor drivers, and tohave less connections between the main board and the motor driver. Also large motordrivers facing upwards would make contact with revolving propellers, and if facingdownwards could cause noise with the ultrasonic sensors. Page 30
    • Unmanned Aerial Vehicle3.2.3 The Brain To avoid the mistakes that occurred in Configuration 2 mentioned in the Testing,Troubleshooting & redesign section the team changed two things mainly. FirstlyTo avoidthe problem of circuit design or re-altering, it was decided that the IC s would be mountedon separate boards that would mount on the main Brain board, much the way PCI slotsare mounted on a normal PC. In our previous design, should any circuit design errors occur,a new board would have to be made, and all components would have to be welded off theold board, and re-welded to the new brain. This takes a lot of time, and it is also potentiallydamaging to the components to be frequently exposed to the welder. Secondly as for havingthe problem of high power rated components alongside low power rated ones in one circuit,optocouplers were used to interface between the Brain board and motor drivers, this ismore thoroughly explained in the previous section 4.6 Motor Drivers . Page 31
    • Unmanned Aerial Vehicle This Main board was designed to accommodate two PIC16LF777s, 4 Motorcontroller boards connected through 4 opto-couplers, a 3-axis accelerometer, 2 dual-axisgyrometers, 5 ultrasonic sensors, a GPS receiver and a RF transceiver. To keep the circuitas small as possible we used the internal 8MHz oscillators available in PIC16LF777 PICsinstead of adding more components to the circuit in the form of crystals and capacitors. Thecircuit is powered by a 9V battery and has a 5V regulator as well as a 3V regulator for all5V Logic components as well as the 3V Logic components to operate. We also added someLEDs to simplify debugging. Later on we manually welded on some wires to two ICSPconnectors to program the two PICs without removing them from the circuit. (As seen inthe previous picture). Page 32
    • Unmanned Aerial Vehicle CONTROL4.1 Introduction The Main PIC is responsible for reading and calculating the orientation of the plane,and accordingly take a decision. The Main PIC has only 3 PWM modules, therefore we usean extra PWM from the Secondary PIC. The Main PIC sends commands to the SecondaryPIC to increase or decrease the power of one PWM output, it also sends the orientation datato be sent through the RF to the base computer station. The Secondary PIC takes the GPSmessages and extracts the required values and sends them to the Main PIC, as well asthrough the RF to the base station. Regarding the control scheme, there are four separateoperation modes:1. Hover Mode2. RC Mode3. GPS Mode4. Tracking ModeIn Hover Mode: Tries to keep the vehicle stable in position. The following pseudocode demonstratesthe operating algorithm.Start up systemRead bias values from IMU sensorsLoop: Read sensors Calculate Angles & Height If(Height<Required Meters) Increase PWM if(Height>Required Meters) Decrease PWM if tilted left Tilt right If tilted right Tilt left If tilted forwards Tilt backwards If tilted backwards Tilt forwardsRepeat loop Page 33
    • Unmanned Aerial VehicleIn RC Mode: The Secondary PIC is the one that receives the RC commands through the RF, thenforwards them to the Main PIC to execute.In GPS Mode: The Secondary PIC takes the GPS messages and extracts the required values andsends it to the Main PIC, and it sends all other useful data through the RF to the basestation. The Main PIC takes decisions according to its coordinates achieved from the GPSfrom the Secondary PIC.In Tracking Mode: The base station receives the Video Feed from the Wireless Camera on board thevehicle and searches for a blue target in view, if it is not found the vehicle will gain altitudeand search again. Once a target is found the plane will descend quickly and hover above thetarget and keep following it. The Secondary PIC receives the commands from the basestation through RF and forwards the commands to the Main PIC which performs therequired actions. Page 34
    • Unmanned Aerial Vehicle4.2 SPI communication SPI communication enables quick communication between two PIC s. One is set asa Master PIC and the other as a slave. Originally one PIC was intended to be used, butfailed. (refer to Testing, Troubleshooting & Design : Configuration 2). The connection is asfollows on the diagram below. The left block represents the Master PIC and the left block isthe slave. A bit is released from the Master SSPSR to SD0, and the slave PIC releases a bitthrough it s SD0 also. The clocks SCK of both PICS are connected together. When a clockpulse rises and falls from the master PIC a bit is transferred. Every consecutive clocktransfers a bit. Once the shift registers reach 8-bits (1 byte) the byte is transferred to theserial input buffer and the shift register is ready to receive data again. Three connections arerequired, CLK to CLK (C3-C3), Master data out to slave data in (C5 C4), and master datain to slave data out (C4 C5). Two registers must be set in both PIC s in order to enable this mode; SSPSTAT andSSPCON. (Actual settings for these registers can be found in APPENDIX B : CONTROLCODE) Page 35
    • Unmanned Aerial VehicleSSPSTAT (Status Register) Page 36
    • Unmanned Aerial VehicleSSPSCON (MSSP Control Register) For desired interrupts bits 6 and 7 of INTCON (Global and peripheral interrupts)should be set. Bit7 of PIE1(SSPIE) should be set. When interrupt occurs bit7 ofPIR1(SSPIR) is set. This occurs if either a byte is successfully transferred, also in case ofcollision occurs or overflow occurs. Page 37
    • Unmanned Aerial Vehicle4.3 Main PIC Implementation Generally as aforementioned, this PIC uses PWM, SPI, and ADC, it decides theorientation and heading of the plane. The following sections divide these tasks and explaineach of these elements independently.4.3.1 Pulse Width Modulation After we have finally tested all our sensors, GPS device and RF devices for correctprocessed data, we can now begin to implement the results as output on the propellersthrough motor control. This is achieved by the use of PWM. In the PIC 16LF777, it hasthree pins for PWM. The control registers used to enable PWM on this PIC are CCP1CON,CCP2CON, CCP3CON, PR2 and most importantly T2CON, since PWM is controlled byTimer 2 in the microcontroller. These three CCPXCON registers let us enable capturemodes, compare modes or PWM. Of course here, we will enable the PWM. Page 38
    • Unmanned Aerial VehicleBit 7: Unimplemented.Bit 6: Unimplemented.Bit 5: Should be set as 0. Second Least Significant bit in PWM mode. (10-bit Resolution).Bit 4: Should be set as 0. First Least Significant bit in PWM mode. (10-bit Resolution).Bit 3: Should be set as 1. (To enable PWM mode).Bit 2: Should be set as 1. (To enable PWM mode).Bit 1: Don t care in PWM. (To enable PWM mode).Bit 0: Don t care in PWM. (To enable PWM mode).The CCPXCON registers will be all set as following:CCP1CON: 0x0F = 0b00001111;CCP2CON: 0x0F = 0b00001111;CCP3CON: 0x0F = 0b00001111; Page 39
    • Unmanned Aerial Vehicle After setting the CCPXCON registers, we must now set the T2CON register wheremost importantly we must enable TIMER2 of the microcontroller and then set the periodwe need to control our DC Brushed Motors in an optimum way using the PR2 register andsetting it with a fixed value. By means of research and supervision, it was decided tocontrol our motors at a frequency of 750Hz (750 times per second).For T2CON, we place the following settings: After setting the CCPXCON registers, we need to now set the T2CON register whichenables TIMER2 in the microcontroller that will then control over the frequency or periodwe need on the Pulse Width Modulation. In order do this we must set the following bits asfollows.Bit 7: Unimplemented.Bit 6: Should be set as 0. (Postscaling will not be needed).Bit 5: Should be set as 0. (Postscaling will not be needed).Bit 4: Should be set as 0. (Postscaling will not be needed).Bit 3: Should be set as 0. (Postscaling will not be needed).Bit 2: Should be set as 1 in order to enable and turn on Timer 2.Bit 1: Should be set as 1. (Since prescale with a value of 16 is required).Bit 0: Should be set as 1. (Since prescale with a value of 16 is required). Page 40
    • Unmanned Aerial Vehicle Our goal to control our motors at around 750Hz. Now since the microcontroller canexecute 2 million instructions per second (500 nanoseconds). Speed should be reduced byprescaling. When you prescale your instructions per second over 16 which is ourmaximum, then we have reduced the frequency to 125 KHz (125000Hz). This is where thePR2 register comes in handy to further reduce frequency to 750Hz.For PR2, we place the following settings: PR2 is an 8-bit register made available in order to control the frequency outputneeded on the DC Brushed Motors. After using the T2CON register for prescaling toreduce frequency to 125 KHz, PR2 register is used to enter a decimal value that will controland limit our frequency to 750Hz. The value to be placed in the PR2 register is calculatedas follows. We divide the 125000 Hz obtained by 750Hz which is what is needed.125000/750 = 166.666667. Since the value to be placed in the PR2 register should be aninteger value and is an 8-bit register and carries no space for a floating point number, 167should be entered after subtracting 1 from it. Therefore,PR2 = 166The equation for PR2 is: round (Fosc / (4 x 16 x Period Required)) - 1Hence, Fosc = 8 x 10^6 PR2 = round(8 x10^6 / ( 4 x 16 x 750)) - 1 PR2 = round(8 x 10^6/ (48000)) - 1 PR2 = round(166.66666667)) - 1 PR2 = 167 - 1 PR2 = 166 Page 41
    • Unmanned Aerial VehicleSetting outputs on the Tri-State Buffers on all ports of the Microcontroller: Since the PWM pins are driving the motors they need to be se as output pins. This isdone by setting the registers TRISB and TRISC.TRISC = 0x00 Hex = 0b00000000.TRISB = 0x00 Hex = 0b00000000.The diagram of the PIC 16LF777 can be used as a reference below for the output pinsCCP1 on Port C2, CCP2 on Port C1, and CCP3 on Port B5.*NOTE: Please see APPENDIX B for the sample code of Pulse Width Modulation and howto control it. Page 42
    • Unmanned Aerial Vehicle4.3.2 ADC Operation Here using the Analog - to - Digital converters is most crucial in order to automateour Unmanned Aerial Vehicle (UAV). For the most part, most or all of our sensors,ultrasonic, gyrometer and accelerometer give us feedback on our control system. TheUltrasonic provides us with a way for collision detection and obstacle avoidance. Theaccelerometer and gyrometer provide us with crucial data to help us stabilize our UAV inmid-air and maintain a static hovering position. It can also help the UAV to auto-level aftertraveling in a certain direction, like a co-pilot. The outputs of those sensors are analog voltages. The Analog - to - digital converterhere helps with converting those outputs into useful data ready to be used and processed bythe microcontroller. In this project we use the 16LF777 PIC by Microchip. It contains anabundant 14 channel 10-bit ADC. We have 11 inputs from those sensors. Five alone for the ultrasonic sensors, placed onthe front, back, left, right, and bottom sides of our UAV for height accuracy. Theultrasonic s range is far as 6.45m (254 inches) and as small as 15cm (6 inches) to aid theUAV in landing due to its blind spot. Six channels are used for 2 Gyrometers and anaccelerometer. Each gyrometer outputs the rate of angular velocity in the X and Y planes,so we need three channels since we have 2 gyrometers. One input/channel will be ignoredfrom the second gyrometer. The accelerometer needs 3 channels since it measuresacceleration in the X, Y, and Z directions. This makes a total of 11 channels. Therefore, 3channels on our 16LF777 microcontroller will not be used out of the 14 channels. In order to set this up in our PIC we must enable certain bits in our control registers ofthe 16LF777 microchip. These control registers are the ADCON0, ADCON1, ADCON2,PIE1, and PIR1 and last but not least the INTCON register to enable our interruptsespecially when the ADIF (AD Interrupt Flag) is set after every conversion in the PIRregister. The result of the Analog-to-Digital Converter is placed in the ADRES (AD Result)register. It consists of 2 8-bit registers, ADRESL (AD Result LOW) and ADRESH (ADResult HIGH). Page 43
    • Unmanned Aerial Vehicle Page 44
    • Unmanned Aerial Vehicle Page 45
    • Unmanned Aerial VehicleFor ADCON0, we place the following settings:Bit 7: <ADCS1> Must be set as 1 since we are using the Internal Oscillator.Bit 6: <ADCS1> Must be set as 1 since we are using the Internal Oscillator.Bit 5: <CHS2> Analog Channel Select bit.Bit 4: <CHS1> Analog Channel Select bit.Bit 3: <CHS0> Analog Channel Select bit.Bit 2: <GO/DONE> A bit that controls the start of conversion or end of conversion.Bit 1: <CHS3> Analog Channel Select bit.Bit 0: <ADON> Turns on the ADC module in the microcontroller.Bits 5,4,3,1 are used to select the channels we need to take our inputs from. Therefore, youneed to toggle through them as we read our values over the output interval time. We startout by reading through channel 0, then 1, then 2, until we reach channel 10 (11 Channels)then go back to Channel 0 to take new readings to process for our new interval. Page 46
    • Unmanned Aerial VehicleFor ADCON1, we place the following settings:Bit 7: <ADFM> Must be set as 1 for Right Justification in the ADRES register. In reading our result from the ADRES register, we read all the 8 bits from ADRESL and the least significant bits of ADRESH and multiply it by 256.Bit 6: <ADCS2> Must be set as 1 since we are using the Internal Oscillator.Bit 5: <VCFG1> Must be set as 0 since our Vref+ is normally the VDD of the PIC.Bit 4: <VCFG0> Must be set as 0 since our Vref- is normally the VDD of the PIC.Bit 3: <PCFG3> Must be set as 0 since we need to enable 11 Channels.Bit 2: <PCFG2> Must be set as 1 since we need to enable 11 Channels.Bit 1: <PCFG1> Must be set as 0 since we need to enable 11 Channels.Bit 0: <PCFG0> Must be set as 0 since we need to enable 11 Channels. The bits 3,2,1,0 of PCFG(X) remain fixed since we are enabling only 11 Channels forthe ADC to read from. The pins where pins AN11, AN12 and AN13 of the microcontroller16LF777 remain digital I/O pins depending on the settings of the Tri-State Buffers for theports.For ADCON2, we place the following settings:Bit 7: Unimplemented.Bit 6: Unimplemented.Bit 5: Must be set as 1, since we wish the conversion to take 12TAD (24 sec).Bit 4: Must be set as 0, since we wish the conversion to take 12TAD (24 sec).Bit 3: Must be set as 1, since we wish the conversion to take 12TAD (24 sec).Bit 2: Unimplemented.Bit 1: Unimplemented.Bit 0: Unimplemented. Page 47
    • Unmanned Aerial Vehicle The reason why 12TAD is necessary here is simply because one TAD is equivalent to2 sec. The acquisition time must not exceed the minimum of 19.72 s which is how longthe ADC before the ADC starts conversion automatically. Therefore, 2 s * 12 = 24 sec, which is how long the ADC needs to acquire our datafrom one input channel. In order to keep the microcontroller working efficiently and processing data withouthaving it constantly polling and wasting processing power on all kinds of data coming inthrough the Sensors, GPS device or RF transceivers, we use interrupts. Concerning oursensors we set the PIE1 control register in our microcontroller. The Analog-to-DigitalInterrupt Enable (ADIE) is bit number 6. We set it to 1. Whenever the ADC finishes aconversion, it will set the Analog-to-Digital Interrupt Flag in (ADIF) to 1 in register PIR1,interrupting the PIC. After we take our reading for the ADC, we must clear the ADIF in thePIR1 register in our software or else the PIC will keep itself running in a loop. Then wemust change our channel through the bits 5, 4, 3, and 1 in the ADCON0 register. When thisis done, we start a new conversion by the setting the bit number 2 (GO/DONE) as 1 in theADCON0 register until the end of conversion is complete and the ADIF is set again callingthe interrupt function in our microcontroller.Setting our inputs on the Tri-State Buffers on all ports of the Microcontroller: Since we have already set our control registers of the ADC module most importantly,we need to set the tri-state buffers on our ports in order to receive our inputs from thesensors. This is done by setting the registers TRISA, TRISB, and TRISE.TRISA = 0xFF Hex = 0b11111111.TRISB = 0x0E Hex = 0b00001110.TRISE = 0x07 Hex = 0b00000111. Page 48
    • Unmanned Aerial Vehicle In the summary of registers shown above, we must be very careful when setting theTRISE register because only the three least significant bits here control the PORTE DataDirection Bus, unlike TRISA where the complete register is used for only 6 pins. If we setthe TRISE = 0xFF, it will cause the PIC to set two interrupt flags IBF and OBF andenable PSP Mode , which will cause PORTD to engage in parallel communication. Thiswill cause the PIC to enter in an infinite loop of interrupts and if the flags are not cleared inthe software. It almost causes the microcontroller to seem to Halt in a sense. Page 49
    • Unmanned Aerial Vehicle4.3.2.1 Ultrasonic Sensors The ultrasonic sensors used on the UAV can detect up to 254 inches 6.45 (meters) andthe minimum distance it can detect due to its blind spot is 6 inches (15 cm). The sensorgenerates a new reading every 49 milliseconds. Since the microcontroller can take readingsmuch faster than the ultrasonic sensor s output, if we take the readings at that speed, it willcause a lot of noise in our program for the UAV, so it is best we take our readings every49 milliseconds to avoid the noise and make sure we have a new reading every time to beput to good use. Every 0.01 Volts on our Ultrasonic sensor represents 1 inch of distance. Therefore, ifthe voltage on the output pin of the ultrasonic sensor is 0.20 Volts, then the distance it readsis 20 inches, therefore it is very simple to use. In order to calculate the distance we need in our PIC 16LF777 we use a very simpleequation which is:Distance (in Hexadecimal) = (Vin/Vref) X (2N) ; where Vin : is the Voltage input coming from the Ultrasonic Sensor. Vref : is the reference voltage from our circuit which is 3.30V N : is the number of bits of the ADC which is 10, therefore is 1024For example, If Vin = 0.50V (which is equivalent to 50 inches read). Vref = 3.30VThen, 0.50/3.30 X 1024 = 155.1515 Hexadecimal In the ADC of the PIC 16LF777, the ADRES (AD Result) register will read 155 andwill truncate the 0.1515. If we take the reading 155 from the ADC and try to convert it back, it will be asfollows: Page 50
    • Unmanned Aerial VehicleVin = (Reading from ADRES Register in HEX / 2N) X Vref Vin = (155/1024) X 3.30V = 0.4995 Volts. Therefore the error is: (1 (0.4995/0.5)) X 100 = 0.1 % which is quite accurate.*NOTE: Please see APPENDIX B for the sample code of the Ultrasonic Sensors. Page 51
    • Unmanned Aerial Vehicle4.3.2.2 GyrometerThe gyrometer used was the IDG300. This IC gives accurate readings of angular velocity.All three angles were needed for control of the UAV, on the x, y and z axes; traditionally inflight labeled as roll, pitch and yaw angles. Angular velocity is measured accurately with asensitivity of 2 mV/ º/s. So every degree of rotation would indicate 0.002V electronically.The first thing to do was to interpret the signals into degrees, 0º - 360º. This IC operates so that if the IC is rotated suddenly then stopped, you would get achange in reading only when the IC is moving, only when there is angular velocity. Thus anadder function is needed to constantly integrate the tilt intervally through the selectedfrequency, as general equation is as follows: SUM SUM new tWhere SUM is initially set to 0. new is the latest reading from the gyro output and T is thesampling period. After the electric signal would be received on the ADC ports of the PIC it would bemultiplied by the following equation to give degrees: 1024 tAngleNew AngleOld Vin * * 3.3 0.62 Also any negative value for tilt had 360 added to it, since simple sin and cosfunctions behave differently to negative values. Accelerometer The accelerometer used was the ADXL330. This gives accurate measures ofacceleration about all three axes. Typical sensitivity of this IC is 300mV/g, so every 1m/s2of acceleration would indicate 30.58mV electronically. Primarily this IC has two mainfunctions. The first is to indicate the initial angles of x and y in reference to the xy planeperpendicular to the gravity vector, so that the UAV can take off from any angled surface,if an accelerometer was not used, the system would always assume that the plane it wastaking off from was always perpendicular to the vector of gravity, causing flight to beunstable. To use the accelerometer as an inclinometer, assuming X and Y are theacceleration values obtained from the corresponding axes on the accelerometer then, simply Page 52
    • Unmanned Aerial Vehicle X -1 X=sin g Y -1 Y=sin g The second use is to produce accurate estimations of acceleration, velocity andposition, for use in the simulation. A fixed reference point is taken, more accurately thefixed axes at the point of takeoff. Acceleration and velocity in reference to that point arecalculated. Distance from that point is calculated, and distance traveled around that point isalso calculated. Considering the accelerometer uses the angles supplied from the gyrometer,a traditional 3D rotational matrix is used to rotate the constantly generated accelerationvectors around the reference axes, so that every value from the accelerometer has a X, Yand Z component on the reference axes.Rotation around the x-axis is defined as : 1 0 0RX( X) = 0 cos X sin X where X is the roll angle 0 sin X cos XRotation around the y-axis is defined as : cos Y 0 sin YRY( Y) = 0 1 0 where Y is the pitch angle sin Y 0 cos YRotation around the z-axis is defined as : cos Z sin Z 0RZ( Z) = sin Z cos Z 0 where Z is the pitch angle 0 0 1Multiplying all these matrices together would give the following matrix: Page 53
    • Unmanned Aerial Vehicle cos Y cos Z cos Y sin Z sin Y 1A sin Y sin X cos Z cos X sin Z sin Y sin X sin Z cos X cos Z sin X cos Y sin Y cos X cos Z sin X sin Z sin Y cos X sin Z sin X cos Z cos X cos Yif X,Y and Z are the acceleration values obtained from the corresponding axes on theaccelerometer then,ReferenceX = Xcos Xcos Y + Y(sin Ycos Xsin Z-sin Xcos Z) + Z(sin Ycos Xcos Z+sin Xsin Z)ReferenceY = Xsin Xcos Y + Y(sin Ysin Xsin Z+cos Xcos Z) + Z(sin Ysin Xcos Z-cos Xsin Z)ReferenceZ = - Xsin Y + Ycos Ysin Z + Zcos Ycos Z Integrating with respect to time once gives velocity, and integrating twice givesposition. Adder functions are used for velocity and position for each reference axes.Another adder function is created taking the absolute value of every acceleration reading,then multiplying them by time twice in order to calculate the distance traveled. All adderfunctions for total rigid body acceleration, velocity, distance from origin and distancetraveled, this simple equation is used. 2 2V alue X Y Z2 Page 54
    • Unmanned Aerial Vehicle4.4 Secondary PIC Implementation Generally as aforementioned, this PIC uses PWM, SPI, USART, and communicateswith an RF module. It handles communication tasks for the Main PIC. It also acts as asecondary PWM module. The following sections divide these tasks and explain each ofthese elements independently.4.4.1 GPS System GPS has become a widely used aid to navigation worldwide, and a useful tool formap-making, land surveying, commerce, and scientific uses. GPS also provides a precisetime reference used in many applications including scientific study of earthquakes, andsynchronization of telecommunications networks. There is a constellation of 30 (earthorbiting satellites as of April 2007) that transmit precise radio signals. Their orbits are setup so that at any given point and time on the earth s surface there are at least six of thesesatellites in reach. A figure below demonstrates the constellation of NAVSTAR GPSsatellites. Page 55
    • Unmanned Aerial Vehicle A GPS receiver calculates its position by measuring the distance between itself andthree or more GPS satellites, using trilateration. Measuring the time delay betweentransmission and reception of each GPS radio signal gives the distance to each satellite,since the signal travels at a known speed. The signals also carry information about thesatellites location. By determining the position of, and distance to, at least three satellites,the receiver can compute its position using trilateration. Receivers typically do not haveperfectly accurate clocks and therefore track one or more additional satellites to correct thereceivers clock error. The figures below briefly explain trilateration, where at the center of each spherethere is a satellite. When two spheres intersect they create lines. When the third sphereintersects it creates a point revealing the location of the receiver. The coordinates are calculated according to the World Geodetic System WGS84coordinate system. Position is determined by latitude and longitude which are basicallyangles, latitude ranges from 0-90 north and south, and longitude ranges from 0-180 westand east. The figures below display latitude and longitude. Page 56
    • Unmanned Aerial Vehicle To calculate its position, a receiver needs to know the precise time. The satellitesare equipped with extremely accurate atomic clocks, and the receiver uses an internalcrystal oscillator-based clock that is continually updated using the signals from thesatellites. GPS satellites continuously transmit almanac and ephemeris at 50bps. The almanacconsists of coarse time information and orbital data (speed and path). The ephemeris givesthe satellites precise orbit. The almanac assists in the acquisition of other satellites. Acomplete almanac transmission is a 37,500 bit navigation message that takes 12.5 minutesto download. This long delay occurs when a new receiver is first turned on. Each satellitetransmits its navigation message with at least two distinct spread spectrum codes: theCoarse / Acquisition (C/A) code, which is freely available to the public, and the Precise (P)code, which is usually encrypted and reserved for military applications. The C/A code is a1,023 bit long pseudo-random code broadcast at 1.023 MHz, repeating every millisecond.Each satellite sends a distinct C/A code, which allows it to be uniquely identified. Page 57
    • Unmanned Aerial Vehicle The receiver identifies each satellites signal by its distinct C/A code pattern, thenmeasures the time delay for each satellite. To do this, the receiver produces an identicalC/A sequence using the same seed number as the satellite (two or more systems usingmatching seeds can generate matching sequences of non-repeating numbers which can beused to synchronize remote systems). By lining up the two sequences, the receiver canmeasure the delay and calculate the distance to the satellite, called the pseudorange. Thepseudoranges are then the time the signal has taken from there to the receiver, multiplied bythe speed of light. The orbital position data from the Navigation Message is then used tocalculate the satellites precise position. Knowing the position and the distance of a satelliteindicates that the receiver is located somewhere on the surface of an imaginary spherecentered on that satellite and whose radius is the distance to it. When four satellites aremeasured simultaneously, the intersection of the four imaginary spheres reveals the locationof the receiver. The orbital position data from the Navigation Message is then used tocalculate the satellites precise position. Knowing the position and the distance of a satelliteindicates that the receiver is located somewhere on the surface of an imaginary spherecentered on that satellite and whose radius is the distance to it. When four satellites aremeasured simultaneously, the intersections of all four imaginary spheres reveal the locationof the receiver. Often, these spheres will overlap slightly instead of meeting at one point. Thereceiver then moves the overlapping pseudoranges with the same amount (regardless ofdistance of receiver to satellite) till an intersection point is created this point is usually themost probable position. This scenario is shown in the following figure. Page 58
    • Unmanned Aerial Vehicle An overlapping pseudorange occurs here. Instead of having one intersection point, aroom is created by all three points of B . All distances are subtracted by the same amount,in this case 0.5, in order to receive an intersection point at A . Point A is considered themost probable point of the receiver. Regarding GPS time as opposed to the conventional second, minute and hour; youonly have seconds, more precisely seconds of the week. In a normal clock when theseconds reach 60 it starts a new minute. In GPS time when the seconds reach 604,800 itstarts a new week, this is calculated by 7(days)*24(hours)*60(minutes)*60(seconds). As for GPS date as opposed to the year, month, and day format of the Juliancalendar, the GPS date is expressed as a week number and a day-of-week number. Theweek number is transmitted as a ten-bit field, and so it becomes zero again every 1,024weeks (19.6 years). GPS week zero started at (00:00:19 TAI) on January 6, 1980 and theweek number became zero again for the first time at on August 21, 1999. This event isknown as a rollover. After a GPS does a full almanac download, GPS systems boot in 3 different modes.Those would be cold start, warm start and hot start. In cold start, time and position areknown within some limits, the almanac is known and the ephemeris is unknown. In warmstart, time and position are known within some limits, the almanac is known, and at leastthree satellite ephemeris are known from the previous operation. In a hot start all ephemerisfor all satellites are known so a hot start occurs. The GPS receiver chooses how to startbased on the time between last turn off and current turn on. If this time was a few minutesthe GPS chooses hot start which takes 1 second, if it was a few hours the choice is warmstart which takes 38 seconds, anything longer than that produces a cold start which takes 42seconds. Most GPS systems have two protocols SirF protocol and NMEA protocol. In ourcase the NMEA protocol was used. NMEA protocol simply contains input messages andoutput messages. (Refer to the NMEA reference manual) Page 59
    • Unmanned Aerial VehicleInput messages selected to initialize the GPS are:$PSRF100,1,4800,8,1,0*0Ern$PSRF103,04,00,02,01*22rn$PSRF105,0*3Frn$PSRF is used for input messages. The star means the following two characters arechecksum, NMEA checksum operates by 16-bit XOR a checksum calculator code is shownin the APPENDIX B : CONTROL CODE, and /r/n represent carriage return and line feed,whose HEX code are 0D 0A. All other fields in between them are data fields for differentsettings.$PSRF100,1,4800,8,1,0*0ErnThis message was used for setting the serial port. 100 in the first field represents serial portsettings. 1 in the second field is for NMEA protocol, 4800 is for baud rate, 8 is for 8 databits, 1 is for 1 stop bit, and 0 is for no parity bit.$PSRF103,04,00,02,01*22rnThis line is used for enabling and disabling output messages, 103 is used for query/controlmode. 04 is used for RMC mode, 02 is used for releasing the message at 2Hz, 01 is used forenabling checksum.$PSRF105,0*3Frn105 is used for development data. The 0 represents debug off should any error occur, sothat our PIC does not receive any unnecessary input. When a GPS is turned off, it s lastsettings before being switched off will be saved in it s battery powered RAM. When turnedon, these settings resume. These input messages were considered necessary in order to setthe serial port correctly for USART communication, RMC mode was chosen because thisone single message had all the necessary information required. The third message is forturning off debug to avoid unnecessary input to the MCU. A 16-bit XOR CRC creator was necessary to give input messages. A JAVA code isdisplayed in the APPENDIX B: CONTROL CODE. Page 60
    • Unmanned Aerial Vehicle Later on a program called SiRF Demo PC GPS Utility v3.83 was found very helpfulfor obtaining latitude and longitude coordinates for our tested range area. It can also beused as an initialization alternative. To initialize your GPS time, you simply click setupthen click GPS Time PC Time as shown in the figure below. Usually the demo startsin SiRF protocol. To switch it to NMEA protocol you simply click action then Switch toNMEA Protocol , to open NMEA Setup. In this window as shown in the figure below, youcan select each message and it s frequency per second. Highlighting checksum is preferredfor message validation. For NMEA, baud rate should be set at 4800bps. After powering offthe GPS receiver, GPS time, message type and frequency are saved. Page 61
    • Unmanned Aerial Vehicle Output messages received from RMC mode (in order) are UTC time, data validity,latitude, north/south indicator, longitude, west/east indicator, velocity over ground in knots,heading measured clockwise from north in degrees, and date A sample output message isshown below:$GPRMC,161229.487,A,3723.2475,N,12158.3416,W,0.13,309.62,120507, ,*10The first two letters following the $ represent the device in use. The GP stands for GPS.There are other devices such as:LC Loran-CTR Transit SATNAVAP Autopilot (magnetic)HC Magnetic heading compassRA RadarSD Depth sounderVW Mechanical speed log Latitude and longitude are displayed in degrees and minutes, At a latitude of 30° N(Cairo, Egypt), the latitude minute = 1847.54m and longitude minute = 1608.1m (distanceschange because the circumference of parallel of latitude changes, Earth is not a cylinder,please refer to http://home.online.no/~sigurdhu/Grid_1deg.htm ), velocity is multiplied by1.852 to change from knots to km/hr. Then course heading in degrees ranging from 0°-360° moving clockwise from north. The final field before the checksum is date. The onlyfields needed were data validity, latitude, longitude, velocity and heading. VTG mode wasdesired to attain height, but during testing, height in MSL (Mean Sea Level) was quiteinaccurate. At a change of height of about 4 meters, the GPS detected a change of height of10 meters which is an error of over 150%. Latitude, longitude velocity and heading aretransmitted via RF to the simulation. Page 62
    • Unmanned Aerial Vehicle A destination in GPS mode is set by pre-inputting a target destination, in the PICprogram, in latitude and longitude. The following steps are taken:1. Y = Target Latitude Present Altitude2. X = Target longitude Present Latitude3. Distance = X2 Y2 1 Y4. TempAngle is obtained by tan XDesired course heading is obtained by the following scheme:Y X Course+ + TempAngle + 0°- - TempAngle + 180°+ - TempAngle + 360° (TempAngle is negative)- + TempAngle + 180° (TempAngle is negative)Resgister Settings Communication between the PIC and GPS system is acheived by the UniversalSynchronous Asynchronous Receiver Transmitter (USART). In this case Asynchronousmode is used. (refer to the PIC 16F777 pdf file, section 11.0 for more detailed information)To enable this serial mode three registers must be set; TXSTA, RCSTA and SPBRG.TXSTA is set in the following manner:Bit 7: 0 Don t care (for Asynchrous mdoe)Bit 6: 0 for 8-bit transmissionBit 5: 0 for transmission enabledBit 4: 0 for Asynchronous modeBit 3: 0 this bit is unimplementedBit 2: 0 for High speedBit 1: 1 for TSR empty (TRMT)Bit 0: 0 not used in 8-bit transmission Page 63
    • Unmanned Aerial Vehicle SPBRG is the simplest where only a value is entered into the register. Consideringasynchronous mode is used and the system is low speed, the following equation is used,where X is the value entered in SPBRG: FOSCX 1 64* BaudRate When a baud rate of 4800bps with a frequency of 8MHz is entered into the equationthe resulting X value is 25.04, so 25 is the value used in SPBRG.The RCSTA register is set in the following manner:Bit 7: 1 for Serial port enabledBit 6: 0 for Enables 8-bit receptionBit 5: 0 Don t care for Asynchronous modeBit 4: 1 to Enable continuous receive (called CREN)Bit 3: 0 Don t care for 8-bit modeBit 2: 0 for no Overrun error(OERR)Bit 1: 0 for no Framing error(FERR)Bit 0: 0 Don t care for 8-bit mode When transmitting input messages to the GPS system to initialize data, the datamessage had to be inserted in the PIC s EEPROM via MPLAB before programming to PIC(an .ECH file can be created with your EEPROM input by exporting a file (MPLAB), thisfile is easier to load than re-inputting every time), because it consumed too much RAM.Data is transmitted bit by bit via the TXREG register, the TSR register must be polled tosee whether the bit was sent out or not when TSR is empty only can u fill in the next bit.Interrupts are undesired in this mode. Page 64
    • Unmanned Aerial Vehicle For Universal Asynchronous reception, the 6th and 7th bit of the INTCON registermust be set, to enable interrupts, along with the 5th bit of register PIE1. An interrupt occurs(bit5 of register PIR is set) under three cases, when a byte is received successfully, when anOERR (Overrun error) or when a FERR (Framing error) occurs. If a FERR occurs themessage is discarded. The message is valid if; the message starts with a $ and ends with0D 0A, the GPS sends an A in the 19th byte, no FERR error occurs, and the CRC check iscorrect. If the message is valid, SPI communication transmits the latitude, longitude andheading to the Main PIC, Also the RF transmits function is called to send this data (for usein the simulator). This code in detail can be seen in APPENDIX B: CONTROL CODE. Page 65
    • Unmanned Aerial Vehicle4.4.2 Radio Transceiver This RF device is called a transceiver in the sense that the same unit can send andreceive, to and from another identical unit. Operating frequency is 2.4GHz, and datatransmission rate can be selected at either 250Kbps or 1Mbps. 250kbps works at a longerrange of 280m but after testing, range proved to be approximately 180m. Also 250kbpsimproves receiver sensitivity. There are two modes direct mode and shock burst mode.Shock burst works at a lower current and relaxed PIC operation. Low current consumptionoccurs by using an onboard FIFO to transmit data at a low rate then transmit at a high rate.PIC resources are saved by having an onboard CRC creator/checker fortransmitting/receiving respectively. Pre-amble, address, and CRC are stored on a buffer onthe RF then transmitted out, instead of letting the PIC do all this work. The transceiver canreceive simultaneously on two different channels. Only one channel was used in thisproject.Pins used Used pins were CE (Chip Enable), CS (Chip Select), CLK (Clock), DR1 (DataReady1), DATA1, Vcc, and GND (1 represents pins pertaining to Channel1). Thetransceiver requires a configuration word of up to 15 bytes. This is done through three pins;CS, CLK and DATA1. Generally CE is turned off, CS is turned on, a delay is done to allowonboard processing, and then data is fed in bit by bit as the clock toggles. The Shock burstconfiguration word is as follows:Shock Burst configuration Word:The section bit[119:16] contains the segments of the configuration register dedicated toShock Burst operational protocol. After VDD is turned on Shock Burst configuration is doneonce and remains set whilst VDD is present. During operation only the first byte forfrequency channel and RX/TX switching need to be changed. Page 66
    • Unmanned Aerial VehiclePLL_CTRLBit 121-120: Controls the setting of the PLL for test purposes. With closed PLL in TX nodeviation will be present. For normal operational mode these two bits must both be low.DATAx_WBit 119 112: DATA2_W: Length of RF package payload section for receive-channel 2.Bit 111 104: DATA1_W: Length of RF package payload section for receive-channel 1.NOTE: The total number of bits in a Shock Burst RF package may not exceed 256!Maximum length of payload section is hence given by: DATAx_W(bits) = 256 (ADDR_W+ CRC)ADDRxBit 103 64: ADDR2: Receiver address channel 2, up to 40 bit.Bit 63 24: ADDR1 ADDR1: Receiver address channel 1, up to 40 bit.*NOTE: Bits in ADDRx exceeding the address width set in ADDR_W are redundant and canbe set to logic 0. Page 67
    • Unmanned Aerial VehicleADDR_W & CRCBit 103 64: ADDR2: Receiver address channel 2, up to 40 bit.Bit 63 24: ADDR1 ADDR1: Receiver address channel 1, up to 40 bit.NOTE: Bits in ADDRx exceeding the address width set in ADDR_W are redundant and canbe set to logic 0.ADDR_W & CRCBit 23 18: ADDR_W: Number of bits reserved for RX address in Shock Burst packages.NOTE: Maximum number of address bits is 40 (5 bytes). Values over 40 in ADDR_W arenot valid.Bit 17: CRC_L: CRC length to be calculated by nRF2401 in Shock Burst. Logic 0: 8 bit CRC Logic 1: 16 bit CRCBit: 16: CRC_EN: Enables on-chip CRC generation (TX) and verification (RX). Logic 0: On-chip CRC generation/checking disabled Logic 1: On-chip CRC generation/checking enabled Page 68
    • Unmanned Aerial VehicleThis section of the configuration word handles RF and device related parameters.Modes:General device configuration:Bit 15: RX2_EN: Logic 0: One channel receive Logic 1: Two channels receiveNOTE: In two channel receive, the nRF2401 receives on two, separate frequencychannels simultaneously. The frequency of receive channel 1 is set in the configurationword bit[7-1], receive channel 2 is always 8 channels (8 MHz) above receive channel 1.Bit 14:Communication Mode: Logic 0: nRF2401 operates in direct mode. Logic 1: nRF2401 operates in Shock Burst modeBit 13: RF Data Rate: Logic 0: 250 kbps Logic 1: 1 Mbps*NOTE: Utilizing 250 kbps instead of 1Mbps will improve the receiver sensitivity by 10 dB.1Mbps requires 16MHz crystal. Page 69
    • Unmanned Aerial VehicleBit 12-10: XO_F: Selects the nRF2401 crystal frequency to be used:Bit 9-8: RF_PWR: Sets nRF2401 RF output power in transmit mode:RF channel & directionBit 7 1: RF_CH#: Sets the frequency channel the nRF2401 operates on.The channel frequency in transmit is given by: ChannelRF =2400MHz + RF_CH# * 1.0MHzRF_CH #: between 2400MHz and 2527MHz may be set. The channel frequency in datachannel 1 is given by: ChannelRF =2400MHz + RF_CH# * 1.0MHz(Receive at PIN#8)RF_CH #: between 2400MHz and 2524MHz may be set.The channel frequency in data channel 2 is given by: ChannelRF =2400MHz + RF_CH# * 1.0MHz + 8MHz(Receive at PIN#4)RF_CH #: between 2408MHz and 2524MHz may be set. Page 70
    • Unmanned Aerial VehicleBit 0: Set active mode: Logic 0: transmit mode Logic 1: receive modeFor more intricate details about the configuration word refer to the nRF2401 datasheet page19.Within Shockburst mode there are four different modes. They are displayed in thefollowing table.ACTIVE MODEThere are two different options in Active mode, Transmit and Receive.Transmit1. When the application MCU has data to send, set CE high. This activates nRF2401 onboard data processing.2. The address of the receiving node (RX address) and payload data is clocked into the nRF2401. The application protocol or MCU sets the speed <1Mbps (ex: 10kbps).3. MCU sets the CE to low, this activates a nRF2401 Shock Burst transmission.4. nRF2401 Shock Burst: RF front end is powered up RF package is completed (preamble added, CRC calculated Data is transmitted at high speed (250 kbps or 1 Mbps configured by user). nRF2401 return to stand-by when finished Page 71
    • Unmanned Aerial VehicleReceive1. Correct address and size of payload of incoming RF packages are set when nRF2401 is configured to Shock Burst RX.2. To activate RX, set CE high.3. After 200ms settling, nRF2401 is monitoring the air for incoming communication.4. When a valid package has been received (correct address and CRC found), nRF2401 removes the preamble, address and CRC bits.5. nRF2401 then notifies (interrupts) the MCU by setting the DR1 pin high.6. MCU may (or may not) set the CE low to disable the RF front end (low current mode).7. The MCU will clock out just the payload data at a suitable rate (ex. 10kbps).8. When all payload data is retrieved nRF2401 sets DR1 low again, and is ready for new incoming data package if CE is kept high during data download. If the CE was set low, a new start up sequence can begin.The following flowchart displays the processes of receiving and transmitting. Page 72
    • Unmanned Aerial VehicleCONFIGURATION MODESimilar to active mode Configuration mode has two options, Configure Transmitter, andConfigure Receiver.Configure Transmitter1. In configure transmitter, CE is turned off, and CS is turned on.2. DATA1 with CLK send the configuration word to the RF.3. A delay of (1ms) is issued to allow ample time for onboard processing.4. Both CE and CS are turned off.Configure Receiver1. In configure receiver, CE is turned off and CS is turned on.2. A delay (1ms) is issued. The configuration is then sent through DATA1 from the PIC as the clock toggles.3. CE and CS are then turned off and a delay (1ms) is used also for onboard processing.4. CE is then left on as to enable receiving.STAND-BY MODE Stand by mode is used to minimize average current consumption while maintainingshort start up times. In this mode, part of the crystal oscillator is active. Currentconsumption is dependent on crystal frequency.POWER DOWN MODE In power down the nRF2401 is disabled with minimal current consumption,typically less than 1µA. Entering this mode when the device is not active minimizesaverage current consumption, maximizing battery lifetime. Page 73
    • Unmanned Aerial VehicleDATA PACKAGE DESCRIPTION Data packages contain four main sections, in MSB order Pre-amble, address,payload and CRC. Pre-amble is either 4 or 8 bits and is added to the data packet. Address isbetween 8 and 40 bits. Payload is the desired data being transmitted or received. CRC iseither 8 or 16 bits and used for validating message. More detail about the data package canbe seen in the table below. For information regarding delays, (please refer to the RF-24G datasheet page22).Recommendations: 1. Delays should be taken very carefully, ample time is required for onboard processing. 2. Sequence of turning on CE and CS should be very accurate, or the transceiver will not operate as desired. 3. Configuration word should be set very carefully. 4. Configuration word entry starts from the MSB to the LSB. 5. This IC is unlike other ICs, it is very sensitive to physical shock and short circuits, three of these units were irreversibly damaged, which in our case cost much time. Page 74
    • Unmanned Aerial Vehicle4.5 RC UNIT The main purpose of this RC Unit besides enabling RC mode, is that the user caninterfere manually should any errors occur, such as vehicle misguidance. This can save thevehicle from possible crashes.1. KEYPAD TESTING Required components are the keypad encoder MM74C923, 0.1uF capacitor, 1uFcapacitor, and a 16 key keypad. The 1uF capacitor determines the debounce key mask. Thisis done by creating a debounce period of 0.01s (delay) of on the encoder. The 0.1uFdetermines the scanning frequency at 400Hz. The encoder has an output enable as whichshould be set at active low. These CMOS key encoders provide all the necessary logic to fully encode an arrayof SPST switches. The keyboard scan can be implemented by either an external clock orexternal capacitor. These encoders also have on-chip pullup devices which permit switcheswith up to 50 KHz on resistance to be used. No diodes in the switch array are needed toeliminate ghost switches. The internal debounce circuit needs only a single external Page 75
    • Unmanned Aerial Vehiclecapacitor and can be defeated by omitting the capacitor. A Data Available output goes to ahigh level when a valid keyboard entry has been made. The Data Available output returnsto a low level when the entered key is released, even if another key is pressed. The DataAvailable will return high to indicate acceptance of the new key after a normal debounceperiod; this two-key rollover is provided between any two switches. An internal registerremembers the last key pressed even after the key is released. The TRI-STATEÉ outputsprovide for easy expansion and bus operation and are LPTTL compatible. Both the keyboard scan rate and the key debounce period by altering the oscillatorcapacitor, COSE, and the key debounce mask capacitor, CMSK. Thus, the MM74C923sperformance can be optimized for many keyboards. The keyboard encoders connect to aswitch matrix that is 4 rows by 4 columns or 5 rows by 4 columns (MM74C923). When nokeys are pressed, the row inputs are pulled high by internal pull-ups and the column outputssequentially output a logic 0 . These outputs are open drain and are therefore low for 25%of the time and otherwise off. The column scan rate is controlled by the oscillator input,which consists of a Schmitt trigger oscillator, a 2-bit counter, and a 2±4-bit decoder. Whena key is pressed, key 0, for example, nothing will happen when the X1 input is off, since Y1will remain high. When the X1 column is scanned, X1 goes low and Y1 will go low. Thisdisables the counter and keeps X1 low. Y1 going low also initiates the key debounce circuittiming and locks out the other Y inputs. The key code to be output is a combination of thefrozen counter value and the decoded Y inputs. Once the key debounce circuit times out,the data is latched, and the Data Available (DAV) output goes high. If, during the keyclosure the switch debounces, Y1 input will go high again, restarting the scan and resettingthe key debounce circuitry. The key may debounce several times, but as soon as the switchstays low for a debounce period, the closure is assumed valid and the data is latched. A key Page 76
    • Unmanned Aerial Vehiclemay also debounce when it is released. To ensure that the encoder does not recognize thisdebounce as another key closure, the debounce circuit must time out before another closureis recognized. The two-key roll-over feature can be illustrated by assuming a key is pressed,and then a second key is pressed. Since all scanning has stopped, and all other Y inputs aredisabled, the second key is not recognized until the first key is lifted and the key debouncecircuitry has reset. The output latches feed TRI-STATE, which is enabled when the OutputEnable (OE) input is taken low.The following circuit schematic wasused to connect the keypad to theencoder.For testing refer to the section 5.1 Testing. Page 77
    • Unmanned Aerial Vehicle TESTING TROUBLESHOOTING & REDESIGN5.1 TESTING In embedded systems, programming involves a lot of debugging, and besidessoftware errors, many hardware errors occur also. Errors such as such as misplaced or loosewiring, close wires, wrong filenames (that simulate and run fine but give never work in acircuit), incorrectly connected hardware or incorrect register settings. When something doesnot work many possibilities come to mind, which makes debugging a tiresome and longprocess. That s why a bottom-down programming approach is much more efficient andtime saving.5.1.1 LED TESTING Since we cannot see any variables during runtime without probably having specialhardware called an ICD. This is the simplest straight forward method one can use fortesting, for fast observations. ACCELEROMETER TESTING In order to test the functionality and the accuracy of the accelerometer readings asimple code was written to light up 4 LEDs in a row as a scale for inclination. The greaterthe angle of inclination the more LEDs turn on. GYROMETER TESTING The same method was applied on the gyrometer as the accelerometer but instead ofmeasuring angle, it measured angular velocity which we would later on integrate to acquirethe displacement angle. Page 78
    • Unmanned Aerial Vehicle5.1.1.3 SPI TESTING In order to test the SPI functionality a couple of LEDs were connected onto theMain and Secondary PIC. These LEDs would light up interchangeably with every messagetransferred through. RC UNIT TESTING Initially the Keypad and it s encoder are connected to four LED s in order toindicate the binary output of what was pressed.This shows results of the first experiment to getthe binary output of the encoder to the LEDsAfter the previous experiment was successful, thenext step was to see if the MCU would workperfectly along with the previous system.This experiment shows the output of the keypadthrough the MCU. The LED s turn on by the MCU,by showing the binary output of the button pressed.LEDs were arranged in order of 4-bits in thisexperiment. Page 79
    • Unmanned Aerial Vehicle5.1.2 LCD TESTING The LCD connected to a PIC was a great method to test individual code segmentsbefore integrating them into a greater whole. SPI, ultrasonic sensors, RF, GPS system, wereall tested individually using this method. The preferable LCD of choice to use is the Hitachi HD44780. It proved simple,efficient and the libraries are readily available in most PIC programming packages. Theconnections are illustrated as follows:Bit 0: Ground (GND).Bit 1: Power (VCC).Bit 2: Variable Resistance (Potentiometer) placed for adjusting contrast.Bit 3: Control line RS (Register Select).Bit 4: Control line R/W (Read/Write).Bit 5: Control line E (Enable).Bit 6: Data Input 0.Bit 7: Data Input 1.Bit 8: Data Input 2.Bit 9: Data Input 3.Bit 10: Data Input 4.Bit 11: Data Input 5.Bit 12: Data Input 6.Bit 13: Data Input 7.Bit 13: VCC for the Backlight.Bit 13: GND for the Backlight.*NOTE: Please see APPENDIX B for the sample code of the Liquid Crystal Display. Page 80
    • Unmanned Aerial Vehicle5.1.2.1 ULTRASONIC TESTING In order to test the blind spot of the ultrasonic sensor and to verify its sensitivity, theoutput from the ultrasonic sensor was connected to a PIC and was measured printed on anLCD for a better view of the oscillations in readings. ACCELEROMETER TESTING After performing the LED test on the accelerometer readings it was required to seethe angle in degrees in a human readable form, so the accelerometer output was measuredand the angle calculated in the PIC and displayed onto an LCD in degrees. Page 81
    • Unmanned Aerial Vehicle5.1.2.3 RC UNIT TESTINGControlling the RF-24G via the keypad A program is configured so options would be sent to the plane via the RF by thetouch of a button from the keypad. The keypad sends an interrupt, that lets the MCU readthe unique value from the encoder. The MCU then identifies which button was pressed andin turn sends a unique message to the RF that the MCU on the plane identifies and actsaccordingly. The following options were in mind.1. Start2. Off3. Hover4. Land5. Left6. Right7. Forward8. Backward9. Land Use of the LCD was integrated into this system, to attain a viewable output that canbe verified. The transceiver not only sends out messages to the plane, but receivesinformation from the plane, regarding latitude and longitude, heading and velocity.This experiment shows the LCDworking with the RF and the keypadsystem. The LCD shows the currentbutton pressed. Page 82
    • Unmanned Aerial Vehicle5.1.2.4 GPS TESTING The final test performed was to see the output of the GPS receiver onto the LCD toverify the USART connection with the GPS receiver.5.1.3 RF TESTING Since LCDs can prove to be buggy and slow an alternative had to be chosen, sincethe RF-24G is much faster than an LCD we tested the outputs and variables of some morecomplex programs than possible with and LCD or LEDs. ULTRASONIC TESTING The Ultrasonic readings taken from the previous ultrasonic program for LCD testingwhere taken and instead of displaying them on the LCD, they were transmitted wireless to acomputer to be displayed onto the screen at a much higher refresh rate. GYROMETER TESTING Initially testing the gyrometer with the LCD was more desirable, but the LCD wasquite slow when keeping up with the gyrometer. Testing it with the RF was a bettersolution. The PIC code integrates the required value and constantly adds the values toprovide the current angle. This value is sent through the RF transmitter. The RF receiver isconnected to the RS232 port. A JAVA program extracts values from the serial port anddisplays it on a GUI. Pictures below show this process. The first picture shows thereceiving RF node, the second shows the general circuit, and the last shows the angle beingdisplayed while the gyro is being tilted. Code for this procedure can be found inAPPENDIX B : CONTROL CODE. Page 83
    • Unmanned Aerial Vehicle Page 84
    • Unmanned Aerial Vehicle5.1.3.3 RC UNIT TESTINGControlling the RF-24G via the keypad A program is configured so options would be sent to the plane via the RF by thetouch of a button from the keypad. The keypad sends an interrupt, that lets the MCU readthe unique value from the encoder. The MCU then identifies which button was pressed andin turn sends a unique message to the RF that the MCU on the plane identifies and actsaccordingly. The following options were in mind.1. Start2. Off3. Hover4. Land5. Left6. Right7. Forward8. Backward9. Land Use of the LCD was integrated into this system, to attain a viewable output that canbe verified. The transceiver not only sends out messages to the plane, but receivesinformation from the plane, regarding latitude and longitude, heading and velocity.This experiment shows the LCDworking with the RF and the keypadsystem. The LCD shows the currentbutton pressed. Page 85
    • Unmanned Aerial Vehicle5.2 PREVIOUS CHASSIS DESIGNS: The team constructed three different chassis. The first three chassis were consideredfailures. Assemblies of all three chassis are explained below, along with our reasons fortheir disapproval. The final design is explained in the section above, conceptual designand physical assembly .PROTOTYPE CHASSIS 1 For initial design balsa wood was used, a very lightweight material, commonly usedin RC planes for its practical characteristics. A rectangular frame was made from severalbalsa planks and glued together with an adhesive agent, super glue. Multiple planks wereused on each side to give rigidity to the plane. The corners were reinforced with triangularpieces of balsa wood which would fit in each of the four inner corners of the plane addingmore rigidity to the welds of the plane. Four equal length legs also made of balsa wood areextended from the plane, in order to give the plane a safe landing. A thick bridge of balsa wood was extended from the mid-section of one of the sidesof the frame to the other side. The top of this bridge was designed to carry ouraccelerometer, gyrometer, camera, GPS and PIC. On the bottom of the bridge we designeda battery compartment. The accelerometer and gyrometer were placed at the absolute centerof the body in the center of the bridge. They were placed on top of each other. They mustboth be placed in the center in order to give accurate readings of acceleration and tilt. Wedecided to put the battery compartment on the bottom of the bridge. Considering it s theheaviest single object on the plane it was put on the bottom of the bridge in the center inorder to lower the center of gravity of the vehicle and provide better balance and easiercontrol. There was an ultrasonic sensor placed on the bottom of the battery compartment inorder to properly detect height. A picture of the first chassis is shown below. It weighed197 grams. Page 86
    • Unmanned Aerial Vehicle In the very end after testing lift with this frame, the chassis was too bulky and heavywhere the plane could barely lift it. Another reason for the lack of power was the triangularpieces of balsa in the corners which blocked airflow under the propellers. The motors werealso delicate in their fastening to the frame. Our team then decided to reconstruct anotherchassis, a lighter one, reduced in size.PROTOTYPE CHASSIS 2 The same design was used again, except the multiple layers were removed to reduceweight and thinner planks were used all over the plane. The rectangular frame was designedso that the when any two adjacent propellers face each other the distance between thepropellers would be a bare 0.5cm. Struts were also added to better fasten the motors. Fourstruts are used to fasten all motors to the corners of the frame with screws, and the strut isfastened to the motor with a plastic belt. The result was a much slighter and sleeker designwith better results than the previous design. This chassis weighed 93 grams. Pictures of thesecond frame (top) and a picture of the first and second frame together showing relativesize (bottom) are placed below. Notice the triangular reinforcements in the first picture(compare to the second) were clipped in order to strengthen the aerodynamic vortex causedunder the rotors. Page 87
    • Unmanned Aerial Vehicle After testing the second chassis we noticed that the triangular reinforcements wereinhibiting lift by disturbing the air vortex created by the propellers. This causedconsideration for a third chassis to be built. Page 88
    • Unmanned Aerial VehiclePROTOTYPE CHASSIS 3 An X-shaped chassis was constructed without the triangular reinforcements, and thesame thin planks were used again. The lengths of the planks were selected once again toleave very low distances between the rotors when they meet. This chassis weighed a mere47.5 grams. The arms of the chassis were trimmed in a triangular shape near the rotors tohelp with air flow. But the chassis was very fragile, and any potential accidents wouldprobably result in a broken chassis and damaged onboard components. The team thenconsidered a carbon-fiber chassis as an alternative, because it suddenly became available ata local hobby vendor. The construction of this chassis is explained thoroughly in theconceptual design and physical assembly section above. A picture of the 3rd chassis isplaced below. Page 89
    • Unmanned Aerial Vehicle5.3 RF DRIVERS5.3.1. Laipac RF TX / RX The Laipac A2ABTAE-D2 transmitter/receiver set was used for communication. Aparallel port sends signals out to the encoder, which in turn encodes signals to thetransmitter, to send to the receiver. The receiver then receives from the transmitter andsends it to a decoder which gives the data to another microcontroller. The transmitter andreceiver circuits were placed on two different boards. Circuit design and actual pictures ofthese circuits are placed below. (On boards below, transmitter is on left, and receiver is onright.) After testing it was decided that this was a very inefficient communication systemfor a variety of reasons. It was very slow, its range was very limited, and it s payload wasvery limited to 1 byte only, not to mention it had no checksum system. The RF-24G provedto be a superior alternative. Page 90
    • Unmanned Aerial Vehicle5.3.2 RF DRIVER The RF transceivers have two separate boards, in this section the one explained isthe board that connects to a parallel port on a land based PC. This board was created inorder to have the RF transceiver and GPS connect to the parallel port of a PC, to be used asan evaluation board for testing. Page 91
    • Unmanned Aerial Vehicle5.4 CONFIGURATION 1: This configuration was used on the second chassis. The PIC of use was the 16F877.It was configured so that one of the PICs was a Main and the other was a Secondary. Thebattery was connected to a specifically designed power distributor. The power distributorthen supplies the large current to all four motor drivers. This board receives power from ourLi-Poly battery and supplies power through wires to the PICs, accelerometer, gyrometer,and motor drivers which in turn supply power to the motors. There were four motor driversone for each of our motors. This motor driver is the same design explained in the analysisand component level design and selection, except one 2SD1062 transistor was used permotor driver, and optocouplers weren t yet implemented. All components of the plane wereintegrated into one large circuit. Circuit designs of the 16F877 driver (top), motor driver(center) and power distributor (bottom) are displayed below. Page 92
    • Unmanned Aerial Vehicle Page 93
    • Unmanned Aerial Vehicle After implementation of this configuration was complete, results were quiteunfavorable for a variety of reasons. Tested lift was not enough to generate substantiallateral thrust. The wattmeter would fluctuate between 6.9V-7.2V and 22A-25A. All theseboards were connected together by wires, and the male pin headers used caused two bigproblems, loose wiring and consecutive pin contact. When any problems happened it wasvery difficult to identify the source of the problem. With extensive testing our powerdistributor board was completely destroyed, (JP2 and JP5 pins and surrounding wires weredestroyed a shown in the figure below) the huge current from the lithium polymer batterycaused the brass board to physically snap from the amount of heat the current generated.Pictures of the burnt power distributor, 16F877 driver, and motor driver (from left to right)are shown below. Page 94
    • Unmanned Aerial Vehicle A picture of the plane in configuration one is placed below. The power distributor isthe leftmost board with the male deans connector attached to it. The 166F877 driver is seenlying on the bridge alongside the RF receiver board. Boards mounted under the rotors arethe motor drivers. The Accelerometer and gyrometers are on the center of the bridge.Ultrasonic sensors are mounted onto hinges and can be seen on the center of each sideplank. The next phase of the project was testing and programming of accelerometer,gyrometer and ultrasonic sensors. This was halted due to the negative results. The teamdecided to revise their chassis, reduce wiring, and alter board configuration. This isexplained in the next section. Page 95
    • Unmanned Aerial Vehicle5.5 CONFIGURATION 2:PIC Implementation : The onboard microprocessor receives signals from the accelerometer, gyrometer,ultrasonic sensors, RF chip and GPS. According to the mode that is being run themicroprocessor controls the four motors accordingly via PWM. The team needed amicroprocessor that can accommodate all these functions. The PIC of choice was the18F4431, a figure of the PIN diagram is placed below. The accelerometer and bothgyrometers are connected to port A, in the ADC pins. The ultrasonic sensors can releaseoutput in three different ways; analog signal, digital signal or by Pulse Width period. Threeultrasonic sensors are placed in the port E ADC pins, releasing analog output, and the lasttwo ultrasonic sensors are placed on port B pins RB6 and RB7. RF outputs connect toDigital I/O pins, except DR1 which connects to a pin with an interrupt function. GPS chipconnects to the serial TX/RX pins of the PIC namely pins RC6 and RC7. A figure of thepin diagram is placed below. Page 96
    • Unmanned Aerial Vehicle This configuration was implemented on the second chassis also. The main idea ofthis configuration was to reduce wiring to a bare minimum. In this configuration female pinheaders were used which are much more stiff in placement and possibility of consecutivepin contact is low. A new microprocessor the 18F4431 was used, this PIC has four PWMmodules thus only one was needed for our UAV system saving weight and wiring andeliminating sync time problems. The PIC, RF chip, accelerometer, gyrometers, motordrivers, and power distribution circuit were integrated into one main board, The brain.The accelerometer and gyrometer were placed in the center of the board and the brain wasto be mounted in the center of the body. The only visible wires were the ones coming fromthe ultrasonic sensors to the brain. The onboard motor driver circuit was edited so that anadditional 2SD1062 was placed in parallel to the previous one to reduce Vce drop. Wiresconnected to the battery were significantly widened to prevent melting. Diagrams of circuitdesign, (top) actual board bottom, (center) and actual board with welded components(bottom) are below. Page 97
    • Unmanned Aerial Vehicle During the making of The brain there was a problem with line wiring of the RFsection, this called to make a new brain. It also came to the team s knowledge thatcombining high rated power components with low power rated components with onecommon ground could be hazardous. The low power rated components could malfunctionor burn. The team decided to design another brain, with motor drivers separated from thecontrol circuit. Also our programmer used to burn the 18F4431 PICS so testing couldn t beimplemented. Page 98
    • Unmanned Aerial Vehicle5.6 Brain Page 99
    • Unmanned Aerial Vehicle5.7 Correcting Gyro Output: Connecting the Gyro directly to the ADC pin of the PIC yielded incorrect results,because the gyro velocity variation signal was very low in voltage, some signals wentunrecognized. Say for example a rotation of 1 degree/sec would produce a 2mV signal onthe corresponding ADC pin. So N = 2mV * 1024/3.3V = 0.6206 which would be roundedto 1. The error here is 61.1%! A quick solution was creating a difference OP-AMP. A circuit schematic isdisplayed below. A potentiometer is connected to a 5V source and GND. Its output connects to thenegative op-amp input, it is adjusted to create a difference, relative to the signal connectedto the positive terminal. VSS determines your voltage output at maximum gain, so that VOUTcan never exceed VSS. The gain in this circuit is simply: RfA R1The VOUT signal in turn is: RfVOUT (V1 V2 ) where VOUT VSS R1 Assuming you had a difference of 0.1V between both OPAMP terminals,Rf=150K & R1=10K , gain would be 15 and Vout would be 1.5V. Sensitivity wouldincrease 15 fold, from 0.002V to 0.03V. In the end the OPAMP was removed because it s Page 100
    • Unmanned Aerial Vehicleoutput proved to be highly unstable, which yielded worse results, so returning to a directsignal and averaging it in the software was a better alternative.Old RFE$4,5,6 and E$7 are silicone diodes, E$1 is 74LS126AP tri-state buffer, the E$8, E$9,E$10, E$11 are 10K pull down resistors, E$3 is the RF connection, and E$2 is the maincircuit connection. E$2 righter most pin is VCC 5V, The E$2 leftermost pin is a 3.3Vconnection beside it is GND, the rest are RF signals coming from the 5V logic. E$4, E$5,E$6, and E$7 are the diodes displayed below. They are connected in this manner becauseDATA1 is bi-directional. The 74LS126AP receives inputs from the PIC, and transmits CE,CS, CLK1 to the RF accordingly. RF interface board Page 101
    • Unmanned Aerial Vehicle FUTURE IMPLEMENTATIONS If there was more time at hand, gyrometer and accelerometer outputs would becorrected in order to reduce if not eliminate output drift. Immediately after that; hovermode, RC mode, GPS mode, and tracking mode would be tested. Ultrasonic sensors wouldbe connected to mechanical servos that move the sensors according to angles. The sensorthat assists in height would be connected to a 3D servo, and all other sensors would beconnected to a 2D servo. This would give us highly accurate estimation of height, andwould detect obstacles that are perpendicular to the gravity vector. (Not objects that areabove or under the UAV.) High powered brushless motors would also be a great variationto our design. Compared to brushed motors, they consume much less power, have higherefficiency, and they have longer life. A long range (near RF range) high resolution camerawould also be a good improvement. If time was ample, our chassis would be redesigned toa circular design where the rotors are placed under the chassis and face downwards. Themain board would be also under the vehicle along with the battery, leaving the upper sideof the plate empty in order to carry objects. Page 102
    • Unmanned Aerial Vehicle CONCLUSION The local market does not have high quality products which were needed for thisproject. Almost all of our components were ordered from abroad. Shipping times for theseparts caused big delays on work time. Unfortunate accidents subjected us to these delays. The most difficult challenge was the race against time and due to the constraints itimposed on this project and due to the nature of the project there was a lot ofundocumented equipments, experimentations, and analysis as time progressed. Considering this project is an embedded system, a bottom-down programmingmethod was used, followed by integrating elements into a greater whole. All singleelements were tested and worked successfully. Only the gyrometer and accelerometer driftswere not corrected and this led to an incomplete project. With more time Kalman filters orPID control techniques could have been implemented. Page 103
    • Unmanned Aerial Vehicle APPENDIX A : COMPONENT DATABASE & CHARACTERISTICSPART NUMBER DESCRIPTION QUANTITYGWS EPS-350C Motor 4EPP1045 Propeller counter-rotating (sold in pairs) 4EHS300 Heat Sync 4TP8000-2S4P Battery 1109D Charger with Dean s connector 1101D Wattmeter with Dean s connector 1106 Blinky battery balancer 1120 13.5V power supply 1549 Blinky-thunderpower adapter 1ADXL330 3-axis accelerometer 1IDG300 2-axis gyrometer 3SEN-00741 IMU 5 Degrees of Freedom 1EM406 20 Channel GPS SiRF III Receiver 2GPS-00653 EM406 SiRF III Evaluation Board - RS232 1RF-24G Radio transceiver 2.4GHz 4WRL-00713 Transceiver Development Node 2WRL-00713 Ultrasonic sensors 5GPS-00653 SirF III Evaluation board 1WS-309-AS Miniature Lightweight Camera kit 200mW 1HD747HOU 8-bit LCD 16*2 1PIC-MCP-USB USB PIC programmer 1 JDM RS232 PIC programmer 22N2222A Transistor 102SD1062 High power Transistor 12TIP120 Transistor 10 Page 104
    • Unmanned Aerial VehiclePC817 Optocoupler 674LS126A Quad tri-state buffer 4HT640 Transmitter Encoder IC 2TWS-434A Radio transmitter 2RWS-434 Radio receiver 2HT-648L Receiver Decoder IC 2MM74C923 16/20 key (Touchpad) Encoder 2L7805CV 5.0V Regulator 30 3.3V Regulator 10 8 MHz Crystal 5 10 MHz Crystal 2 16 MHz Crystal 1 20 MHz Crystal 5 32 MHz Crystal 2 37 MHz Crystal 1 40 MHz Crystal 1 1 1W Resistor 4 3.4K Resistor 5 100 Resistor 30 1.5K Resistor 8 330 Resistor 20 15 5W Resistor 8 10K Resistor 10 3.3K Resistor 8 100K Potentiometer 4 1M Potentiometer 3 22pF Capacitor 20 10uFCapacitor 5 100nF Capacitor 5 0.33uF Capacitor 6 470uF Capacitor 518F4431 MCU Mirocontroller unit 5V 40MHz (max) Page 105
    • Unmanned Aerial Vehicle16F877 MCU Mirocontroller unit 5V 20MHz (max)16F877A MCU Mirocontroller unit 5V 20MHz (max)16LF877 MCU Mirocontroller unit (3/5)V 10MHz (max)16LF777 MCU Mirocontroller unit (3/5)V 10MHz (max Carbon Fiber tubes rectangular (1cm*1cm) 90cm 1 Carbon Fiber tubes cylindrical (Diameter = 1cm) 1 90cm Epoxy (Hardener & Resin) 1 Ecuadorian Balsa wood (10cm*1cm) 90cm 2 Ecuadorian Balsa wood (1cm*1cm) 90cm 3 Ecuadorian Balsa wood (2.5cm*0.6cm) 90cm 5 Ecuadorian Balsa wood (2.5cm*1cm) 90cm 3 Ecuadorian Balsa wood (10cm*0.6cm) 90cm 2DT830 Digital Multimeter (Avometer) 3 Page 106
    • Unmanned Aerial Vehicle APPENDIX B : CONTROL CODEJAVARF WITH PARALLEL PORTimport parport.ParallelPort;import javax.swing.*;import java.awt.event.*;import java.awt.*;class keytest extends JFrame implements KeyListener{ JTextField keyText = new JTextField(1); JTextField function = new JTextField(30); JLabel action = new JLabel("Action"); JLabel keyLabel = new JLabel("Press To Start"); ParallelPort lpt1 = new ParallelPort(0x378); // 0x378 address for a port int j=0; keytest() { super("KeyTest"); keyText.addKeyListener(this); setSize(350, 100); getContentPane().setLayout(new GridLayout(4,1)); getContentPane().add(keyLabel); getContentPane().add(keyText); getContentPane().add(action); getContentPane().add(function); setVisible(true); } private void sleeper() { try { lpt1.write(j); Thread.sleep(1000); // in miliseconds } catch(InterruptedException e) { keyLabel.setText("You numbnut you did this :-"+e.toString()); } } public void keyPressed(KeyEvent input) { /*int[] receiver = new int[30]; Page 107
    • Unmanned Aerial Vehicle int toggler; int j=0; toggler = lpt1.read(); if (toggler>=128) { for(int i=0;i<12;i++) receiver[i]=lpt1.read(); }*/ int j=0; char key = input.getKeyChar(); keyLabel.setText("You pressed " + key); keyText.setText(""); int aByte=0; if(key==a) { aByte=8+1; // BINARY = 1001 sleeper(); lpt1.write(aByte);// sleeper(); function.setText("Increasing Power"); } else if(key==z) { aByte=8+2; // BINARY = 1010 sleeper(); lpt1.write(aByte);// sleeper(); function.setText("Decreasing Power"); } else if(input.getKeyCode()==input.VK_UP) { aByte=8+3; // BINARY = 1011 sleeper(); lpt1.write(aByte);// sleeper(); function.setText("Forward " ); } else if(input.getKeyCode()==input.VK_DOWN) { aByte=8+4; // BINARY = 1100 sleeper(); lpt1.write(aByte);// sleeper(); function.setText("Backward"); } else if(input.getKeyCode()==input.VK_LEFT) { aByte=8+5; // BINARY = 1101 sleeper(); lpt1.write(aByte); Page 108
    • Unmanned Aerial Vehicle// sleeper(); function.setText("Left Direction"); } else if(input.getKeyCode()==input.VK_RIGHT){ aByte=8+6; // BINARY = 1110 sleeper(); lpt1.write(aByte);// sleeper(); function.setText("Right Direction"); } else function.setText("WRONG KEY!");// for(int i=0;i<2000;i++); // to reduce frequency of parallel port to PIC// aByte=00;// lpt1.write(aByte); } public void keyTyped(KeyEvent txt) { // do nothing } public void keyReleased(KeyEvent txt) { // do nothing } public static void main(String[] arguments) { keytest frame = new keytest(); }}JAVA CRC CHECKERimport javax.swing.*;import java.awt.event.*;import java.awt.*;public class NMEAparser extends JFrame implements ActionListener{ private JPanel back,north; private JTextField input,output; private JButton crc; public NMEAparser() { north=new JPanel(); back=new JPanel(new BorderLayout()); Page 109
    • Unmanned Aerial Vehicle getContentPane().add(back); input=new JTextField(30); output=new JTextField(8); output.setEditable(false); north.add(input); north.add(output); back.add(north,BorderLayout.NORTH); crc=new JButton("Calculate Checksum"); back.add(crc,BorderLayout.EAST); setSize(500,100); setVisible(true); setDefaultCloseOperation(EXIT_ON_CLOSE); crc.addActionListener(this);}public void actionPerformed(ActionEvent e){ String text=input.getText(); char crcResult=0; int i=0; while(i<text.length()) { if(text.charAt(i)==$) { i++; continue; } if(text.charAt(i)==*) break; crcResult^=text.charAt(i); i++; } int crcResultHex[]=new int[2]; crcResultHex[0]=(int)(crcResult&0x0F); crcResult>>=4; String result; crcResultHex[1]=(int)(crcResult&0x0F); if(crcResultHex[0]>9) result=String.valueOf((char)(crcResultHex[0]-10+A)); else result=String.valueOf(crcResultHex[0]); if(crcResultHex[1]>9) result=String.valueOf((char)(crcResultHex[1]-10+A))+result; else result=String.valueOf(crcResultHex[1])+result; output.setText(result);}public static void main(String args[]){ new NMEAparser(); Page 110
    • Unmanned Aerial Vehicle }}Ultrasonic Code:int i=0;void interrupt(){ int i=0; if (PIR1.ADIF == 1) { if((ADRESL+(ADRESH*256)) <= 41) { PORTB.f0 = 1; } else { PORTB.f0 = 0; } PIR1.ADIF = 0; INTCON = 0xC0; PIE1 = 0x40; } ADRESL = 0; ADRESH = 0; delay_ms(50); ADCON0.GO = 1;}void main(){ INTCON = 0xC0; OPTION_REG = 0X80; PIR1 = 0x00; PIE1 = 0x40; ADCON1 = 0xCE; ADCON0 = 0x01; TRISA = 0x01; TRISB = 0x00; TRISC = 0x00; TRISD = 0x00; TRISE = 0x00; PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; Page 111
    • Unmanned Aerial Vehicle ADCON0.GO = 1; TMR0=0; while(1);}Tests 5 Ultrasonic sensorsint i = 0;void chooseChannel(){ if (i > 4) { i = 0;} if (i == 0) { ADCON0 = 0b00000001;} else if (i == 1) { ADCON0 = 0b00001001;} else if (i == 2) { ADCON0 = 0b00010001;} else if (i == 3) { ADCON0 = 0b00011001;} else if (i == 4) { ADCON0 = 0b00100001;}}void interrupt(){ int j=0; if (PIR1.ADIF == 1) { if((ADRESL+(ADRESH*256)) > 41) { if (i == 0) { PORTB.f0 = 0; } else if(i == 1) { PORTB.f1 = 0; } else if (i == 2) { PORTB.f2 = 0; } else if (i == 3) { Page 112
    • Unmanned Aerial Vehicle PORTB.f3 = 0; } } else if((ADRESL+(ADRESH*256)) <= 41) { if (i == 0) { PORTB.f0 = 1; } else if(i == 1) { PORTB.f1 = 1; } else if(i == 2) { PORTB.f2 = 1; } else if(i == 3) { PORTB.f3 = 1; } } ADRESL = 0x00; ADRESH = 0x00; PIR1.ADIF = 0; INTCON = 0xC0; PIE1 = 0x40; } //i=(i+1)%4; //ADCON0=(ADCON0&0b11000001)|(i<<3); i++; chooseChannel(); for (j=0;j<40;j++); ADCON0.GO = 1;}void main(){ INTCON = 0xC0; OPTION_REG=0X80; PIR1 = 0x00; PIE1 = 0x40; ADCON1 = 0xC2; ADCON0 = 0x01;TRISA = 0xFF;TRISB = 0x00;TRISC = 0x00;TRISD = 0x00;TRISE = 0xFF; Page 113
    • Unmanned Aerial Vehicle PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; ADCON0.GO = 1; TMR0=0; while(1);}Ultrasonic LED Gaugeint i = 0;void chooseChannel(){ if (i > 1) { i = 0;} if (i == 0) { ADCON0 = 0b00000001;} else if (i == 1) { ADCON0 = 0b00001001;}}void interrupt(){ int j=0; if (PIR1.ADIF == 1) { if((ADRESL+(ADRESH*256)) <= 25) { if (i == 0) { PORTC.f4 = 0; PORTC.f5 = 0; PORTC.f6 = 1; PORTC.f7 = 0; } else if(i == 1) { PORTD.f5 = 0; PORTD.f6 = 0; PORTD.f4 = 1; PORTC.f7 = 0; } Page 114
    • Unmanned Aerial Vehicle}else if((ADRESL+(ADRESH*256)) < 41){ if (i == 0) { PORTC.f4 = 0; PORTC.f6 = 1; PORTC.f5 = 1; PORTC.f7 = 0; } else if(i == 1) { PORTD.f4 = 1; PORTD.f6 = 0; PORTD.f5 = 1; PORTC.f7 = 0; }}else if((ADRESL+(ADRESH*256)) < 80 ){ if (i == 0) { PORTC.f5 = 1; PORTC.f6 = 1; PORTC.f4 = 1; PORTC.f7 = 0; } else if(i == 1) { PORTD.f4 = 1; PORTD.f5 = 1; PORTD.f6 = 1; PORTC.f7 = 0; }}else if((ADRESL+(ADRESH*256)) > 80 ){ if (i == 0) { PORTC.f5 = 0; PORTC.f6 = 0; PORTC.f4 = 0; PORTC.f7 = 1; } else if(i == 1) { PORTD.f4 = 0; PORTD.f5 = 0; PORTD.f6 = 0; Page 115
    • Unmanned Aerial Vehicle PORTC.f7 = 1; } } ADRESL = 0x00; ADRESH = 0x00; PIR1.ADIF = 0; INTCON = 0xC0; PIE1 = 0x40; } delay_ms(50); i++; chooseChannel(); for (j=0;j<100;j++); ADCON0.GO = 1;}void main(){ INTCON = 0xC0; OPTION_REG=0X80; PIR1 = 0x00; PIE1 = 0x40; ADCON1 = 0xC4; ADCON0 = 0x01; TRISA = 0x03; TRISB = 0x00; TRISC = 0x00; TRISD = 0x00; TRISE = 0x00; PORTA = 0; PORTB = 0; PORTC = 0; PORTD = 0; PORTE = 0; ADCON0.GO = 1; TMR0=0; while(1);}Ultrasonic with LCD:int i = 0;int USRead = 0;char count = 0; Page 116
    • Unmanned Aerial Vehiclechar *Text = "Range: ";char *Text1 = "IN";char str1[7];unsigned double temp = 0.00;void interrupt(){ if(count == 0) { count++; Lcd8_Config(&PORTB,&PORTD,3,2,0,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1, 1, Text); Lcd8_Out(1, 15, Text1); } if(PIR1.ADIF == 1) { USRead = (ADRESL + (ADRESH*256)); temp = USRead*0.48828125; temp*=100; for(i=0;i<6;i++) { if(i==2) continue; str1[5-i] = (((char)temp)%10)+0; temp = temp/10; } str1[6]=0; str1[3]=.; Lcd8_Out(1, 8, str1); PIR1.ADIF = 0; INTCON = 0xC0; PIE1 = 0xC0; } ADRESL = 0; ADRESH = 0; delay_ms(50); ADCON0.GO = 1;}void main(){ INTCON = 0xC0; OPTION_REG = 0x80; PIR1 = 0x00; PIE1 = 0x40; ADCON1 = 0xCE; ADCON0 = 0x01; Page 117
    • Unmanned Aerial Vehicle TRISA = 0x01; TRISB = 0x00; TRISC = 0x00; TRISD = 0x00; TRISE = 0x00; PORTA = 0x00; PORTB = 0x00; PORTC = 0x00; PORTD = 0x00; PORTE = 0x00; ADCON0.GO = 1; TMR0 = 0; while(1);}LCD:unsigned char *text = "RCIDIOTS by";unsigned char *text1 = "mikroElektronica";void main(){ TRISB = 0; // PORTB is output TRISD = 0; // PORTD is output // Initialize LCD at PORTB and PORTD with custom pin settings Lcd8_Config(&PORTB,&PORTD,3,2,1,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1, 1, text); Lcd8_Out(2, 1, text1); while(1);}GPS with LCD:char *init = "Initializing....";int i = 0;int j = 0;int row = 0;int count = 0;int column = 0;unsigned char temp1;unsigned char temp[38]; Page 118
    • Unmanned Aerial Vehicleunsigned char count1;void interrupt(){ if(count == 0) { count++; Lcd8_Config(&PORTB,&PORTD,3,2,0,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1,1,init); INTCON.T0IE=0; INTCON.T0IF=0; SPBRG = 25; TXSTA = 0x00; RCSTA = 0x90; PIR1 = 0x00; PIE1 = 0x20; } if (PIR1.RCIF == 1) { PORTC.f5=~PORTC.f5; temp1 = RCREG; if (temp1 == $) { count1 = 0; row = 1; column = 1; i++; } else { temp[0]=temp1; temp[count1]=RCREG; count1=(count1+1)%37; i++; if(i == 38) { for (j=0;j<38;j++) { if ((column == 16)&&(row == 1)) {row = 2; column = 1;} else if ((column == 16)&&(row == 2)) {row = 1; column = 1;} Lcd8_Chr(row, column, temp[j]); column++; } i = 0; PIR1.RCIE = 0; row = 1; Page 119
    • Unmanned Aerial Vehicle column = 1; count1 = 0; temp[count1]=$; } } if(temp1 == $) { PORTC.f4=~PORTC.f4;} PIR1.RCIF = 0; PIR1.RCIE = 0; PIR1.RCIE = 1; RCSTA = 0x90; INTCON = 0xC0; } INTCON = 0xC0;}void main(){ temp[37]=0; INTCON = 0xC0; OPTION_REG = 0x80; TMR0=0; INTCON.T0IE=1; TRISA=0x00; TRISB=0x00; TRISC=0x80; TRISD=0x00; TRISE=0x00; PORTA=0; PORTB=0; PORTC=0; PORTD=0; PORTE=0; while(1);}PWM:unsigned char flag;void interrupt(){ if(INTCON.RBIF == 1) { INTCON.RBIF = 0; PORTA = ~PORTA; } Page 120
    • Unmanned Aerial Vehicle}void main(){ flag=0; INTCON=0xC8; T2CON=0x07; CCP1CON=0x0F; CCP2CON=0x0F; CCP3CON=0x0F; PR2 = 255; TRISB = 0x00; TRISC = 0x00; TRISE = 0x00; PORTB = 0x00; //CCPR1L = 0; //CCPR2L = 0; while(1) { if(flag==0) { CCPR1L++; CCPR2L++; CCPR3L++; PORTC.f0=~PORTC.f0; } else if(flag==1) { CCPR1L--; CCPR2L--; CCPR3L--; PORTC.f3=~PORTC.f3; } if(CCPR1L == PR2) { flag=1; } else if(CCPR1L == 0) { flag=0; } delay_ms(100); }} Page 121
    • Unmanned Aerial VehicleMath Processing power://///////////////////////////////////////////////////////Test on the math operations to find out how long//////////////////////////////////////////////////////////it takes to do one sin operation and later tested to/////////////////////////////////////////////////////////find out how long it would take for all operations.//double x = 30.0;//double y = 0.0;//double b = 0.0;//double a = 0.0;//double u = 0.0;//double v = 0.0;double X = 25.2;double Y = 50.5;double T = 75.7;double ReferenceX = 0.0;double ReferenceY = 0.0;double ReferenceT = 0.0;void alex(){ //PORTC = ~PORTC; //x = 30.0; ReferenceX = X*cos(Y)*cos(T) + Y*cos(Y)*sin(T) - T*sin(T); ReferenceY = X*(sin(Y)*sin(X)*cos(T)-cos(X)*sin(T)) +Y*(sin(Y)*sin(X)*sin(T)+cos(X)*cos(T)) + T*sin(X)*cos(Y); ReferenceT= X*(sin(Y)*cos(X)*cos(T)+sin(X)*sin(T)) + Y*(sin(Y)*cos(X)*sin(T)-sin(X)*cos(T)) + T*cos(X)*cos(Y); //y = sin(x); //b = cos(x); //u = log(x); //v = 6.45*y; PORTB = 0xFF; PORTC=0;}void main(){ TRISC=0; TRISB=0; PORTC=0xFF; alex(); while(1);}Test the payload and change the the configurationunsigned char data_array[29];unsigned char comand;void configure_transmitter(void){ Page 122
    • Unmanned Aerial Vehicle unsigned char i,j; unsigned char config_setup[14], temp; TRISC = 0b00000000; PORTC.f5 = 0; PORTC.f4 = 1; delay_ms(1); config_setup[0] = 0b00000100; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; config_setup[3] = 0xe7; config_setup[4] = 0x00; config_setup[5] = 0x00; config_setup[6] = 0x00; config_setup[7] = 0x00; config_setup[8] = 0xe7; config_setup[9] = 0x00; config_setup[10] = 0x00; config_setup[11] = 0x00; config_setup[12] = 0x00; config_setup[13] = 0xe8; for (j = 14; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTC.f6 = config_setup[j-1].f7; PORTC.f5 = 1; PORTC.f5 = 0; config_setup[j-1] <<= 1; } } delay_ms(1); PORTC.f7 = 0; PORTC.f4 = 0; TRISC = 0b11111111;}void transmit_data(void){ unsigned char i, j, temp, rf_address; TRISC = 0b00000000; PORTC.f7 = 1; delay_ms(1); rf_address = 0b11100111; for(i = 0 ; i < 8 ; i++) { PORTC.f6 = rf_address.f7; PORTC.f5 = 1; PORTC.f5 = 0; rf_address <<= 1; } for(i = 0 ; i < 29 ; i++) { Page 123
    • Unmanned Aerial Vehicle temp = data_array[i]; for(j = 0 ; j < 8 ; j++) { PORTC.f6 = temp.f7; PORTC.f5 = 1; PORTC.f5 = 0; temp <<= 1; } } PORTC.f7 = 0; TRISC = 0b11111111;}void main(){unsigned char x; TRISC = 0b11111111; PORTC = 0b00000000; TRISB = 0b00000001; PORTB = 0b00000000; TRISA = 0b00000000; TRISD = 0b00000000; PORTD = 0b00000000; TRISE = 0b00000000; TRISB = 0b00000001; INTCON = 0b11010000; configure_transmitter(); delay_ms(50); while(1) ; } void interrupt() { Lcd8_Config(&PORTB,&PORTD,3,2,1,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1, 1, "hi ... We are IN"); delay_ms(1000); Lcd8_Cmd(LCD_CLEAR); if(INTCON.INTF == 1) comand=PORTC; if (comand==0x00) { data_array[0]=A; data_array[1]=P; data_array[2]=R; data_array[3]=2; data_array[4]= ; Lcd8_Out(2, 1, "Button # 0"); } if (comand==0x01) { Page 124
    • Unmanned Aerial Vehicle data_array[0]=A; data_array[1]=P; data_array[2]=R; data_array[3]=2; data_array[4]= ; data_array[5]=P; data_array[6]=e; data_array[7]=t; data_array[8]=e; data_array[9]=r; data_array[10]= ; data_array[11]=A; data_array[12]=l; data_array[13]=e; data_array[14]=x; data_array[15]= ; Lcd8_Out(2, 1, "Button # 1"); }if (comand==0x02){ data_array[0]=U; data_array[1]=A; data_array[2]=V; data_array[3]= ; data_array[4]= ; data_array[5]=P; data_array[6]=e; data_array[7]=t; data_array[8]=e; data_array[9]=r; data_array[10]= ; data_array[11]=A; data_array[12]=l; data_array[13]=e; data_array[14]=x; data_array[15]= ; data_array[16]=R; data_array[17]=i; data_array[18]=y; data_array[19]=a; data_array[20]=d; Lcd8_Out(2, 1, "Button # 2");}if (comand==0x03){ data_array[0]=U; data_array[1]=A; data_array[2]=V; data_array[3]= ; Page 125
    • Unmanned Aerial Vehicle data_array[4]= ; data_array[5]=P; Lcd8_Out(2, 1, "Button # 3"); } transmit_data(); delay_ms(50); INTCON.INTF=0; }Test rf with key pad and lcdunsigned char data_array[4];unsigned char comand;void main(){unsigned char x; TRISC = 0b11111111; PORTC = 0b00000000; TRISB = 0b00000001; PORTB = 0b00000000; TRISA = 0b00000000; TRISD = 0b00000000; PORTD = 0b00000000; TRISE = 0b00000000; TRISB = 0b00000001; INTCON = 0b11010000; configure_transmitter(); while(1); } void interrupt() { Lcd8_Config(&PORTB,&PORTD,3,2,1,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); Lcd8_Out(1, 1, "hi ... We are IN"); Lcd8_Cmd(LCD_CLEAR); delay_ms(100); if(INTCON.INTF == 1) comand=PORTC; if (comand==0x00) { data_array[0]=0x12; data_array[1]=0x34; data_array[2]=0xAB; data_array[3]=0xcd; Lcd8_Out(1, 1, "Peter"); } if (comand==0x01) Page 126
    • Unmanned Aerial Vehicle { data_array[0]=A; data_array[1]=P; data_array[2]=R; data_array[3]=2; Lcd8_Out(1, 1, "Alex"); } if (comand==0x02) { data_array[0]=U; data_array[1]=A; data_array[2]=V; data_array[3]= ; Lcd8_Out(1, 1, "Riyad"); } if (comand==0x03) { data_array[0]=U; data_array[1]=A; data_array[2]=V; data_array[3]= ; Lcd8_Out(1, 1, "Ruyan"); } transmit_data(); delay_ms(50); INTCON.INTF=0; }Test rf with interruptunsigned char data_array[4];unsigned char comand;void configure_receiver(void){ unsigned char i,j; unsigned char config_setup[3], temp; TRISD = 0b00000000; PORTD.f0 = 0; PORTC.f0 = 1; delay_ms(1); config_setup[0] = 0b00000101; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTD.f1 = config_setup[j-1].f7; PORTD.f2 = 1; PORTD.f2 = 0; Page 127
    • Unmanned Aerial Vehicle config_setup[j-1] <<= 1; } } PORTD.f0 = 0; PORTC.f0 = 0; TRISD = 0b00000010; delay_ms(1); PORTD.f0 = 1; PORTC.f0 = 0;}void configure_receiver2(void){ unsigned char i,j; unsigned char config_setup[3], temp; TRISD = 0b00000000; PORTD.f0 = 0; PORTC.f0 = 1; delay_ms(1); config_setup[0] = 0b00000101; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTD.f1 = config_setup[j-1].f7; PORTD.f2 = 1; PORTD.f2 = 0; config_setup[j-1] <<= 1; } } PORTD.f0 = 0; PORTC.f0 = 0; TRISD = 0b00000010; delay_ms(1); PORTD.f0 = 1; PORTC.f0 = 0;}void receive_data(void){ unsigned char i, j, temp; PORTD.f0 = 0; data_array[0] = 0x00; data_array[1] = 0x00; data_array[2] = 0x00; data_array[3] = 0x00; for(i = 0 ; i < 4 ; i++) { for(j = 0 ; j < 8 ; j++) { temp <<= 1; temp.f0 = PORTD.f1; PORTD.f2 = 1; PORTD.f2 = 0; Page 128
    • Unmanned Aerial Vehicle } data_array[i] = temp; } PORTD.f0 = 1;}void main(){unsigned char x; TRISC = 0b00000000; PORTC = 0b00000000; TRISB = 0b00000000; PORTB = 0b00000000; TRISA = 0b00000000; TRISD = 0b00000000; PORTD = 0b00000000; TRISE = 0b00000000; TRISB = 0b00000001; for (x = 0; x < 3; x++) { PORTB.f1 = 1; delay_ms(25); PORTB.f1 = 0; PORTB.f3 = 1; delay_ms(25); PORTB.f3 = 0; PORTB.f4 = 1; delay_ms(25); PORTB.f4 = 0; } configure_transmitter(); delay_ms(50); PORTB.f1 = 1; while(1); } void interrupt() { if(INTCON.INTF == 1) { configure_transmitter(); delay_ms(50); transmit_data(); delay_ms(50); configure_receiver2(); delay_ms(50); PORTB.f5=1; if ((data_array[0] == 0x12) && (data_array[1] == 0x34) && (data_array[2] ==0xAB) && (data_array[3] == 0xCD)) { Page 129
    • Unmanned Aerial Vehicle if (PORTB.f4 == 1) { PORTB.f4 = 0; PORTB.f1 = 1; } else if (PORTB.f3 == 1) { PORTB.f3 = 0; PORTB.f4 = 1; } else if (PORTB.f1 == 1) { PORTB.f1 = 0; PORTB.f3 = 1; } } INTCON.INTF=0; } }Test the rf trans and rec.unsigned char data_array[4];void main(){unsigned char x; TRISC = 0b00000000; PORTC = 0b00000000; TRISB = 0b00000000; PORTB = 0b00000000; TRISA = 0b00000000; TRISD = 0b00000000; PORTD = 0b00000000; TRISE = 0b00000000; TRISB = 0b00000001; for (x = 0; x < 3; x++) { PORTB.f1 = 1; delay_ms(25); PORTB.f1 = 0; PORTB.f3 = 1; delay_ms(25); PORTB.f3 = 0; PORTB.f4 = 1; delay_ms(25); PORTB.f4 = 0; } PORTB.f1 = 1; Page 130
    • Unmanned Aerial Vehicle while(1) { configure_transmitter(); transmit_data(); PORTB.f5 = 1 ; configure_receiver(); delay_ms(50); if(PORTB.f0 == 1) { receive_data(); PORTB.f5 = 0 ; if ((data_array[0] == 0x12) && (data_array[1] == 0x34) && (data_array[2] ==0xAB) && (data_array[3] == 0xCD)) { if (PORTB.f4 == 1) { PORTB.f4 = 0; PORTB.f1 = 1; } else if (PORTB.f3 == 1) { PORTB.f3 = 0; PORTB.f4 = 1; } else if (PORTB.f1 == 1) { PORTB.f1 = 0; PORTB.f3 = 1; } } } }}Test the rf with ultra sonicint i=0;int x[4];int j=1;unsigned char data_array[4];void interrupt(){ int i=0; if (PIR1.ADIF == 1) { Page 131
    • Unmanned Aerial Vehicle x[j]=((((ADRESL+(ADRESH*256)/1024))*3)*2.54); j++; if (j==3) { j=0; transmit_data(); delay_ms(50); PORTB.f4 = 1; delay_ms(50); PORTB.f4 = 0; } if((ADRESL+(ADRESH*256)) <= 68) { PORTB.f5 = 1; } else { PORTB.f5 = 0; } PIR1.ADIF = 0; INTCON = 0xC0; PIE1 = 0x40; } ADRESL = 0; ADRESH = 0; delay_ms(50); ADCON0.GO = 1;}void main(){ INTCON = 0xC0; OPTION_REG = 0X80; PIR1 = 0x00; PIE1 = 0x40; ADCON1 = 0xCE; ADCON0 = 0x01;TRISA = 0x01;TRISB = 0x00;TRISC = 0x00;TRISD = 0x00;TRISE = 0x00;PORTA = 0;PORTB = 0;PORTC = 0;PORTD = 0;PORTE = 0;configure_transmitter(); Page 132
    • Unmanned Aerial Vehicle ADCON0.GO = 1; TMR0=0; while(1);}Accelerometer angle measurment & gyrometer angularvelocity measurement with output on LEDsdouble result,iresult;void main(){ TRISA = 0;TRISB = 0;TRISC = 0;TRISD = 0; TRISE = 0; PORTA = 0;PORTB = 0;PORTC = 0;PORTD = 0;PORTE = 0; INTCON=0xC0; TRISA=0b00000001; ADCON0 = 0b01000001; ADCON1 = 0b11000000; delay_ms(2000); ADCON0.GO=1; PORTD.f0=1; while(ADCON0.GO==1); ADCON0 = 0x01; iresult=(ADRESH<<8)+ADRESL; PORTD.f0=0; PIE1 = 0x40; while(1);}void interrupt(){ if(PIR1.ADIF==1) { PORTD.f1=~PORTD.f1; result=iresult-(ADRESH<<8)-ADRESL; if(result<-1) { PORTC=8; } else if(result>1) { PORTC=2; } else PORTC=1; if(result>10) { PORTC=8+16; Page 133
    • Unmanned Aerial Vehicle } if(result>33) { PORTC=8+16+32; } if(result>66) { PORTC=8+16+32+64; } if(result<-10) { PORTC=8+4; } if(result<-33) { PORTC=8+4+2; } if(result<-66) { PORTC=8+4+2+1; } ADCON0 = 0b01000001; ADCON1 = 0b11000000; PIR1.ADIF=0; ADCON0.GO=1; }}Gyrometer angle calculation with integration andsending result through RF.double result,iresult,reading,treading = 0;unsigned char count = 0;char text[4];char data_array[4];int i = 0;void transmit_data2(){ unsigned char i, j, temp, rf_address; TRISC = 0b00000000; PORTC.f7 = 1; delay_ms(1); rf_address = 0b11100111; for(i = 0 ; i < 8 ; i++) { PORTC.f6 = rf_address.f7; PORTC.f5 = 1; PORTC.f5 = 0; Page 134
    • Unmanned Aerial Vehicle rf_address <<= 1; } for(i = 0 ; i < 4 ; i++) { temp = data_array[i]; for(j = 0 ; j < 8 ; j++) { PORTC.f6 = temp.f7; PORTC.f5 = 1; PORTC.f5 = 0; temp <<= 1; } } PORTC.f7 = 0;}void bootup(){ OSCCON=0b01111000; while(OSCCON.f2==0);}void main(){ TRISA = 1;TRISB = 0;TRISC = 0;TRISD = 0; TRISE = 0; PORTA = 0;PORTB = 0;PORTC = 0;PORTD = 0; PORTE = 0; bootup(); PORTD.f0=1; delay_ms(1000); configure_transmitter(); PORTD.f0=0; delay_ms(3000); data_array[0]=T; data_array[1]=E; data_array[2]=S; data_array[3]=T; transmit_data2(); delay_ms(1000); data_array[0]=1; data_array[1]=2; data_array[2]=3; data_array[3]=4; transmit_data2(); delay_ms(1000); data_array[0]=A; data_array[1]=P; data_array[2]=R; data_array[3]=2; transmit_data2(); delay_ms(1000); INTCON=0xC0; Page 135
    • Unmanned Aerial Vehicle TRISA=0b00000001; ADCON0 = 0b01000001; ADCON1 = 0b11000000; ADCON2 = 0b00101000; delay_ms(3000); ADCON0.GO=1; while(ADCON0.GO==1); iresult=(ADRESH<<8)+ADRESL; PIR1.ADIF=0; PIE1 = 0x40; ADCON0.GO=1; while(1);}void interrupt(){ if(PIR1.ADIF==1) { reading=(ADRESH<<8)+ADRESL-iresult; treading+=reading; i++; if(i==400) { treading/=400; i=0; if(treading<-2) result+=treading*0.266308593; if(treading>2) result+=treading*0.266036; reading=result; for(count=0;count<3;count++) { text[2-count]=0+(char)reading%10; reading/=10; } data_array[1]=text[0]; data_array[2]=text[1]; data_array[3]=text[2]; if(result<0) data_array[0]=-; else data_array[0]=+; transmit_data(); } PIR1.ADIF=0; ADCON0.GO=1; }} Page 136
    • Unmanned Aerial VehicleSPI with gyro angle calculation with integration &sending through RF.Master#include "constants.h"double xGyro,yGyro,IxGyro,IyGyro,altUltra,xAngle,yAngle,temp;char i = 0, count = 0;void bootup(){ OSCCON=0b01111000; while(OSCCON.f2==0);}void initialize_ports(){ TRISA=0x3F; TRISE=0x07; TRISB=TRISC=TRISD=0; PORTB=PORTC=PORTD=0;}void initialize_spi_master(){ TRISC.f4=1; SSPSTAT=0b01000000; SSPCON=0b00100000;}void debugging_code(){ PORTC.f6=1; PORTC.f7=0; delay_ms(5000); PORTC.f7=1; PORTC.f6=0;}void setup_adc(){ ADCON0=0b01100001; ADCON1=0xC2; ADCON2=0b00101000;}void get_initial_values(){ ADCON0.GO=1; while(ADCON0.GO==1); IxGyro=(ADRESH<<8)+ADRESL; ADCON0=0b01011001; ADCON0.GO=1; while(ADCON0.GO==1); Page 137
    • Unmanned Aerial Vehicle IyGyro=(ADRESH<<8)+ADRESL; ADCON0=0b01100001;}void set_interrupts(){ INTCON=0xC0; OPTION_REG=0b10000010; PIR1.ADIF=0; PIE1.ADIE=1;}void start(){ ADCON0.GO=1;}void init_pwm(){ SSPBUF=INIT_PWM; CCP1CON=CCP2CON=CCP3CON=0x0F; CCPR1L=CCPR2L=CCPR3L=0; T2CON=0b00000111; PR2=167;}void increase_front_left(){ if(CCPR2L<PR2) CCPR2L++;}void decrease_front_left(){ if(CCPR2L>0) CCPR2L--;}void increase_front_right(){ SSPBUF=INCREASE_PWM;}void decrease_front_right(){ SSPBUF=DECREASE_PWM;}void increase_back_left(){ if(CCPR1L<PR2) CCPR1L++;}void decrease_back_left(){ if(CCPR1L>0) CCPR1L--; Page 138
    • Unmanned Aerial Vehicle}void increase_back_right(){ if(CCPR3L<PR2) CCPR3L++;}void decrease_back_right(){ if(CCPR3L>0) CCPR3L--;}void increase_pwm(){ increase_front_right(); increase_front_left(); increase_back_left(); increase_back_right();}void decrease_pwm(){ decrease_front_right(); decrease_front_left(); decrease_back_left(); decrease_back_right();}void tilt_right(){ decrease_front_right(); increase_front_left(); increase_back_left(); decrease_back_right();}void tilt_left(){ increase_front_right(); decrease_front_left(); decrease_back_left(); increase_back_right();}void tilt_forward(){ decrease_front_right(); decrease_front_left(); increase_back_left(); increase_back_right();}void tilt_backward(){ increase_front_right(); Page 139
    • Unmanned Aerial Vehicle increase_front_left(); decrease_back_left(); decrease_back_right();}void spin_right(){ decrease_front_right(); increase_front_left(); decrease_back_left(); increase_back_right();}void spin_left(){ increase_front_right(); decrease_front_left(); increase_back_left(); decrease_back_right();}void wait_for_transmission(){ while(PIR1.SSPIF==0); PIR1.SSPIF=0;}void configure_transmitter(){ wait_for_transmission(); SSPBUF=CONFIGURE_TRANSMITTER;}void configure_receiver(){ wait_for_transmission(); SSPBUF=CONFIGURE_RECEIVER;}void send_double(){ wait_for_transmission(); SSPBUF=DOUBLE_MSG;}void transmit_data(double data){ wait_for_transmission(); SSPBUF=TRANSMIT_DATA; wait_for_transmission(); SSPBUF=data; temp=data/256; wait_for_transmission(); SSPBUF=temp; temp=temp/256; wait_for_transmission(); Page 140
    • Unmanned Aerial Vehicle SSPBUF=temp; temp=temp/256; wait_for_transmission(); SSPBUF=temp;}void transmit_data2(double data){ wait_for_transmission(); SSPBUF=TRANSMIT_DATA; wait_for_transmission(); SSPBUF=data; temp=data/256; wait_for_transmission(); SSPBUF=temp; temp=temp/256; wait_for_transmission(); SSPBUF=temp; temp=temp/256; wait_for_transmission(); SSPBUF=temp; PORTC.f7=1;}void main(){ bootup(); initialize_ports(); initialize_spi_master(); setup_adc(); delay_ms(3000); configure_transmitter(); delay_ms(50); temp=T*256*256*256+E*256*256+S*256+T; transmit_data(temp); delay_ms(1000); temp=1*256*256*256+2*256*256+3*256+4; transmit_data(temp); delay_ms(1000); temp=A*256*256*256+P*256*256+R*256+2; transmit_data(temp); delay_ms(1000); init_pwm(); delay_ms(10000); debugging_code(); get_initial_values(); set_interrupts(); start(); while(1);}void interrupt() Page 141
    • Unmanned Aerial Vehicle{ if(PIR1.ADIF==1) { if(i==0) { xGyro+=(ADRESH<<8)+ADRESL-IxGyro; ADCON0=0b01100001; count++; if(count==400) { count=0; xGyro/=400; if(xGyro>2) xAngle+=xGyro*0.266036; if(xGyro<-2) xAngle+=xGyro*0.266308593; xGyro=0; transmit_data2(xAngle); if(SSPCON.WCOL==1) PORTC.f6=1; } ADCON0.GO=1; i=0; } else if(i==1) { yGyro+=(ADRESH<<8)+ADRESL-IyGyro; ADCON0=0b01110001; if(count==0) { yGyro/=50; if(yGyro<-1) { tilt_forward(); PORTC.f7=0; } if(yGyro>1) { tilt_backward(); PORTC.f7=1; } } ADCON0.GO=1; i=2; TMR0=0; } else if(i==2) { altUltra+=(ADRESH<<8)+ADRESL; Page 142
    • Unmanned Aerial Vehicle ADCON0=0b01100001; if(count==0) { altUltra/=50; if(altUltra<133) increase_pwm(); if(altUltra>133) decrease_pwm(); xGyro=0; yGyro=0; altUltra=0; } ADCON0.GO=1; i=0; count=(count+1)%50; } PIR1.ADIF=0; } if(INTCON.T0IF==1) { INTCON.T0IF=0; INTCON.T0IE=0; ADCON0.GO=1; }}Slave#include "constants.h"unsigned char msg,i = 0;double double_msg;unsigned char data_array[4];unsigned char bytes = 0;void bootup(){ OSCCON=0b01111000; while(OSCCON.f2==0);}void initialize_ports(){ PORTA=0; PORTE=0; TRISA=0; TRISE=0; TRISB=TRISC=TRISD=0; PORTB=PORTC=PORTD=0;}void initialize_spi_slave(){ Page 143
    • Unmanned Aerial Vehicle TRISC.f4=1; TRISC.f3=1; SSPSTAT=0b01000000; SSPCON=0b00100101;}void debugging_code(){ PORTB.f3=1; PORTB.f5=0; delay_ms(2000); PORTB.f5=1; PORTB.f3=0;}void set_interrupts(){ INTCON=0xC0; PIR1.SSPIF=0; PIE1.SSPIE=1;}void init_pwm(){ CCP1CON=0x0F; CCPR1L=0; T2CON=0b00000111; PR2=167;}void increase_pwm(){ if(CCPR1L<PR2) CCPR1L++; PORTB.f5=1;}void decrease_pwm(){ if(CCPR1L>0) CCPR1L--; PORTB.f5=0;}void receive_char(){}void receive_int(){}void receive_double(){ PIR1.SSPIF=0; PIE1.SSPIE=0; while(PIR1.SSPIF==0); Page 144
    • Unmanned Aerial Vehicle PIR1.SSPIF=0; data_array[i]=SSPBUF; double_msg=data_array[i]; i++; while(PIR1.SSPIF==0); PIR1.SSPIF=0; data_array[i]=SSPBUF; double_msg+=data_array[i]*256; i++; while(PIR1.SSPIF==0); PIR1.SSPIF=0; data_array[i]=SSPBUF; double_msg+=data_array[i]*256*256; i++; while(PIR1.SSPIF==0) PIR1.SSPIF=0; data_array[i]=SSPBUF; double_msg+=data_array[i]*256*256*256; i=0; transmit_data(); PIE1.SSPIE=1;}void prepare_transmit_data(){ bytes=3;}void interrupt(){ if(PIR1.SSPIF==1) { if(bytes==0) { msg=SSPBUF; switch(msg) { case INIT_PWM:init_pwm();break; case INCREASE_PWM:increase_pwm();break; case DECREASE_PWM:decrease_pwm();break; case CONFIGURE_TRANSMITTER:configure_transmitter2();break; case CONFIGURE_RECEIVER:configure_receiver();break; case TRANSMIT_DATA:prepare_transmit_data();break; } } else { data_array[3-bytes]=SSPBUF; bytes--; if(bytes==0) { Page 145
    • Unmanned Aerial Vehicle if(msg==TRANSMIT_DATA) transmit_data2(); PORTB=0xFF; } } } PIR1.SSPIF=0;}void main(){ bootup(); initialize_ports(); ADCON1=0x0F; PORTB=0xFF; delay_ms(1000); configure_transmitter(); delay_ms(1000); PORTB=0; data_array[0]=A; data_array[1]=L; data_array[2]=E; data_array[3]=X; delay_ms(1000); PORTB=0xFF; transmit_data(); delay_ms(1000); PORTB=0; initialize_spi_slave(); set_interrupts(); debugging_code(); while(1);}Constants.h#define INIT_PWM 1#define INCREASE_PWM 2#define DECREASE_PWM 3#define CONFIGURE_TRANSMITTER 4#define CONFIGURE_RECEIVER 5#define INT_MSG 6#define CHAR_MSG 7#define DOUBLE_MSG 8#define TRANSMIT_DATA 9#define UP 10#define DOWN 11#define SENDING 12#define IDLE 13#define WAITING_FOR_ACK 14 Page 146
    • Unmanned Aerial VehiclePIC PWM with interruptsMasterunsigned char dir=0;unsigned char msg;void setup_COMM_SEND(){ TRISD=0;}void setup_COMM_RECEIVE(){ PORTD=0; TRISD=0xFF;}void clock_COMM(){ delay_ms(5000);}void hello(){ setup_COMM_SEND(); PORTD=0xFF; clock_COMM(); setup_COMM_RECEIVE(); while(PORTD.f7==0);}void receive_ACK(){ if(PORTD==0xFF) return; PORTC.f0=1; while(1);}void send_Byte(unsigned char msg){ setup_COMM_SEND(); PORTD=msg; clock_COMM(); setup_COMM_RECEIVE(); while(PORTD.f7==0); if(PORTD==0xFF) return; PORTC.f0=1; while(1);}void setup_PWM(){ Page 147
    • Unmanned Aerial Vehicle send_Byte(SETUP_PWM); T2CON=0b00000111; CCP1CON=0b00001111; CCP2CON=0b00001111; CCPR1L=0; CCPR2L=0;}void setup_COMM(){ hello(); receive_ACK();}void setup_INTERRUPTS(){ INTCON=0b11000000;}void setup_ADC(){ send_Byte(SETUP_ADC); ADCON0=0b01000001; ADCON1=0b11000001;}void increase_PWM(){ send_Byte(INCREASE_PWM); CCPR1L++; CCPR2L++; if(CCPR1L>167) dir=1;}void decrease_PWM(){ send_Byte(DECREASE_PWM); CCPR1L--; CCPR2L--; if(CCPR1L==0) dir=UP;}void main(){ TRISC=0; setup_INTERRUPTS(); setup_COMM(); setup_PWM(); setup_ADC(); while(1) { delay_ms(500); if(dir==UP) Page 148
    • Unmanned Aerial Vehicle increase_PWM(); else decrease_PWM(); }}Slaveunsigned char dir=0;unsigned char msg;void setup_COMM_TRANSMIT(){ TRISD=0; TRISB.f0=0;}void setup_COMM_RECEIVE(){ TRISD=0xFF; TRISB.f0=1;}void clock_COMM(){ delay_ms(2000);}void send_ACK(){ setup_COMM_TRANSMIT(); PORTD=0xFF; PORTB.f0=1; clock_COMM(); PORTB.f0=0; PORTD=0; setup_COMM_RECEIVE();}void receive_Byte(){ msg=PORTD|0x80; send_ACK();}void setup_INTERRUPTS(){ INTCON=0b11010000; OPTION_REG=0b10000000;}void setup_COMM(){ setup_COMM_RECEIVE(); while(PORTB.f0==0); msg=PORTD|0x80; Page 149
    • Unmanned Aerial Vehicle if(msg==HELLO) { send_ACK(); return; } PORTC.f0=1; while(1);}void setup_PWM(){ T2CON=0b00000111; CCP1CON=0b00001111; CCP2CON=0b00001111; CCPR1L=0; CCPR2L=0;}void setup_ADC(){ ADCON0=0b01000001; ADCON1=0b11000001;}void increase_PWM(){ CCPR1L++; CCPR2L++; if(CCPR1L>167) dir=1;}void decrease_PWM(){ CCPR1L--; CCPR2L--; if(CCPR1L==0) dir=0;}void command(){ switch(msg) { case INCREASE_PWM:increase_PWM();break; case DECREASE_PWM:decrease_PWM();break; case SETUP_PWM:setup_PWM();break; case SETUP_ADC:setup_ADC();break; }}void interrupt(){ if(INTCON.INTF==1) { Page 150
    • Unmanned Aerial Vehicle receive_Byte(); command(); INTCON.INTF=0; }}void main(){ TRISC=0; setup_COMM(); setup_INTERRUPTS(); while(1);}Base Station RF receiver codeunsigned char data_array[4],x;void boot_up(){ OSCCON = 0b01110000; while(OSCCON.f2 == 0); ANSEL = 0b00000000; CMCON = 0b00000111; PORTA = 0b00000000; TRISA = 0b00111100; PORTB = 0b00000000; TRISB = 0b11000101;}void configure_receiver(){ unsigned char i,j; unsigned char config_setup[3], temp; PORTA = 0b00000000; TRISA = 0b00111000; PORTA.f6 = 0; PORTA.f0 = 1; delay_ms(1); config_setup[0] = 0b00000101; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTA.f2 = config_setup[j-1].f7; PORTA.f1 = 1; PORTA.f1 = 0; config_setup[j-1] <<= 1; } } Page 151
    • Unmanned Aerial Vehicle PORTA.f6 = 0; PORTA.f0 = 0; PORTA = 0b00000000; TRISA = 0b00111100; delay_ms(1); PORTA.f6 = 1; PORTA.f0 = 0;}void receive_data(void){ unsigned char i, j, temp; PORTA.f6 = 0; data_array[0] = 0x00; data_array[1] = 0x00; data_array[2] = 0x00; data_array[3] = 0x00; for(i = 0 ; i < 4 ; i++) { for(j = 0 ; j < 8 ; j++) { temp <<= 1; temp.f0 = PORTA.f2; PORTA.f1 = 1; PORTA.f1 = 0; } data_array[i] = temp; //Store this byte } if (PORTB.f4 == 1) { PORTB.f4 = 0; PORTB.f1 = 1; } else if (PORTB.f3 == 1) { PORTB.f3 = 0; PORTB.f4 = 1; } else if (PORTB.f1 == 1) { PORTB.f1 = 0; PORTB.f3 = 1; } }PORTA.f6 = 1;}void send_data_USART(){ unsigned char i; for(i=0;i<4;i++) { TXREG=data_array[i]; Page 152
    • Unmanned Aerial Vehicle while(TXSTA.TRMT==0); }}void stop_receiver(){ PORTA.f6=0;}void start_receiver(){ PORTA.f6=1;}void main(){ TRISA=0; TRISB=0; PORTA=0; PORTB=0; boot_up(); for (x = 0; x < 3; x++) { PORTB.f1 = 1; delay_ms(25); PORTB.f1 = 0; PORTB.f3 = 1; delay_ms(25); PORTB.f3 = 0; PORTB.f4 = 1; delay_ms(25); PORTB.f4 = 0; } PORTB.f1 = 1; SPBRG = 25; TXSTA = 0b00100010; RCSTA = 0b10010000; configure_receiver(); while(1) { delay_ms(50); if(PORTA.f3==1) { receive_data(); stop_receiver(); send_data_USART(); start_receiver(); } }} Page 153
    • Unmanned Aerial VehicleBase Station RF transmitter code V2unsigned char data_array[4],x,i;void boot_up(){ OSCCON = 0b01110000; while(OSCCON.f2 == 0); ANSEL = 0b00000000; CMCON = 0b00000111; PORTA = 0b00000000; TRISA = 0b00111100; PORTB = 0b00000000; TRISB = 0b11000101;}void configure_transmitter(void){ unsigned char i,j; unsigned char config_setup[3], temp; PORTA = 0b00000000; TRISA = 0b00111000; PORTA.f6 = 0; PORTA.f0 = 1; delay_ms(1); config_setup[0] = 0b00000100; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTA.f2 = config_setup[j-1].f7; PORTA.f1 = 1; PORTA.f1 = 0; config_setup[j-1] <<= 1; } } delay_ms(1); PORTA.f6 = 0; PORTA.f0 = 0;}void configure_transmitter2(){ unsigned char i,j; unsigned char config_setup[3], temp; PORTA = 0b00000000; TRISA = 0b00111000; PORTA.f6 = 0; PORTA.f0 = 1; delay_ms(1); config_setup[0] = 0b00000100; config_setup[1] = 0b01001110; Page 154
    • Unmanned Aerial Vehicle config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTA.f2 = config_setup[j-1].f7; PORTA.f1 = 1; PORTA.f1 = 0; config_setup[j-1] <<= 1; } } delay_ms(1); PORTA.f6 = 0; PORTA.f0 = 0;}void transmit_data(void){ unsigned char i, j, temp, rf_address; PORTA.f6 = 1; delay_ms(1); rf_address = 0b11100111; for(i = 0 ; i < 8 ; i++) { PORTA.f2 = rf_address.f7; PORTA.f1 = 1; PORTA.f1 = 0; rf_address <<= 1; } for(i = 0 ; i < 4 ; i++) { temp = data_array[i]; for(j = 0 ; j < 8 ; j++) { PORTA.f2 = temp.f7; PORTA.f1 = 1; PORTA.f1 = 0; temp <<= 1; } } PORTA.f6 = 0;}void transmit_data2(){ unsigned char i, j, temp, rf_address; PORTA.f6 = 1; delay_ms(1); rf_address = 0b11100111; for(i = 0 ; i < 8 ; i++) { PORTA.f2 = rf_address.f7; Page 155
    • Unmanned Aerial Vehicle PORTA.f1 = 1; PORTA.f1 = 0; rf_address <<= 1; } for(i = 0 ; i < 4 ; i++) { temp = data_array[i]; for(j = 0 ; j < 8 ; j++) { PORTA.f2 = temp.f7; PORTA.f1 = 1; PORTA.f1 = 0; temp <<= 1; } } PORTA.f6 = 0;}void configure_receiver(){ unsigned char i,j; unsigned char config_setup[3], temp; PORTA = 0b00000000; TRISA = 0b00111000; PORTA.f6 = 0; PORTA.f0 = 1; delay_ms(1); config_setup[0] = 0b00000101; config_setup[1] = 0b01001110; config_setup[2] = 0b00100011; for (j = 3; j > 0; j--) { for(i = 0 ; i < 8 ; i++) { PORTA.f2 = config_setup[j-1].f7; PORTA.f1 = 1; PORTA.f1 = 0; config_setup[j-1] <<= 1; } } PORTA.f6 = 0; PORTA.f0 = 0; PORTA = 0b00000000; TRISA = 0b00111100; delay_ms(1); PORTA.f6 = 1; PORTA.f0 = 0;}void receive_data(void){ unsigned char i, j, temp; PORTA.f6 = 0; data_array[0] = 0x00; Page 156
    • Unmanned Aerial Vehicle data_array[1] = 0x00; data_array[2] = 0x00; data_array[3] = 0x00; for(i = 0 ; i < 4 ; i++) { for(j = 0 ; j < 8 ; j++) { temp <<= 1; temp.f0 = PORTA.f2; PORTA.f1 = 1; PORTA.f1 = 0; } data_array[i] = temp; } PORTA.f6 = 1;}void send_data_USART(){ unsigned char i; for(i=0;i<4;i++) { TXREG=data_array[i]; while(TXSTA.TRMT==0); }}void stop_receiver(){ PORTA.f6=0;}void start_receiver(){ PORTA.f6=1;}void main(){ TRISA=0; TRISB=0; PORTA=0; PORTB=0; boot_up(); for (x = 0; x < 3; x++) { PORTB.f1 = 1; delay_ms(25); PORTB.f1 = 0; PORTB.f3 = 1; delay_ms(25); PORTB.f3 = 0; Page 157
    • Unmanned Aerial Vehicle PORTB.f4 = 1; delay_ms(25); PORTB.f4 = 0; } PORTB.f1 = 1; SPBRG = 25; TXSTA = 0b00100010; RCSTA = 0b10010000; configure_transmitter(); delay_ms(1000); data_array[0]=A; data_array[1]=L; data_array[2]=E; data_array[3]=X; transmit_data2(); delay_ms(1000); PIR1.RCIF=0; PIE1.RCIE=1; INTCON=0xC0; while(1);}void interrupt(){ if(PIR1.RCIF==1) { data_array[i]=RCREG; i=(i+1)%4; if(i==0) { transmit_data(); } }}SPI PWM codeMaster#include "constants.h"unsigned char dir;void Init_Pwm(){ SSPBUF=INIT_PWM; T2CON=0b00000111; CCP1CON=0b00001111; CCP2CON=0b00001111; CCPR1L=0; CCPR2L=0; Page 158
    • Unmanned Aerial Vehicle PR2=255; dir=UP;}void Increase_Pwm(){ SSPBUF=INCREASE_PWM; if(CCPR1L<PR2) CCPR1L++; if(CCPR2L<PR2) CCPR2L++; else dir=DOWN;}void Decrease_Pwm(){ SSPBUF=DECREASE_PWM; if(CCPR1L>0) CCPR1L--; if(CCPR2L>0) CCPR2L--; else dir=UP;}void main(){ TRISA=0; TRISB=0; TRISC=0; TRISE=0; PORTA=0; PORTB=0; PORTC=0; PORTE=0; TRISC.f4=1; SSPSTAT=0b01000000; SSPCON=0b00100000; TRISD=0; delay_ms(5000); Init_Pwm(); while(1) { if(dir==UP) Increase_Pwm(); else Decrease_Pwm(); delay_ms(10); }} Page 159
    • Unmanned Aerial VehicleSlave#include "constants.h"unsigned char msg;void main(){ TRISA=0; TRISB=0; TRISC=0; TRISE=0; PORTA=0; PORTB=0; PORTC=0; PORTE=0; INTCON=0xC0; TRISC.f3=1; TRISC.f4=1; SSPSTAT=0b01000000; SSPCON=0b00100101; PIE1.SSPIE=1; TRISD=0; PORTD=0; while(1);}void Init_Pwm(){ T2CON=0b00000111; CCP1CON=0b00001111; CCP2CON=0b00001111; CCPR1L=0; CCPR2L=0; PR2=255;}void Increase_Pwm(){ if(CCPR1L<PR2) CCPR1L++;}void Decrease_Pwm(){ if(CCPR1L>0) CCPR1L--;}void interrupt(){ if(PIR1.SSPIF==1) { msg=SSPBUF; Page 160
    • Unmanned Aerial Vehicle if(CCPR1L<50) PORTD=1; else if(CCPR1L<100) PORTD=3; else if(CCPR1L<150) PORTD=7; else if(CCPR1L<200) PORTD=15; else PORTD=31; if(msg==INIT_PWM) init_Pwm(); else if(msg==INCREASE_PWM) Increase_Pwm(); else if(msg==DECREASE_PWM) Decrease_Pwm(); PIR1.SSPIF=0; }}GPS testing with RFchar *work = "it worked";unsigned char l=0,discard=0,i=0,gflag=0,count=0,outar[75];unsigned char check=0,crc1,crc2,crc;int glat=0,glong=0,gvel=0,ghead=0;void main(){ INTCON = 0xC0; OPTION_REG = 0x80; TMR0=0; INTCON.T0IE=1; TRISA=0x00; TRISB=0x00; TRISC=0x80; TRISD=0x00; TRISE=0x00; PORTA=0; PORTB=0; PORTC=0; PORTD=0; PORTE=0; while(1);}void interrupt(){ if(count == 0) Page 161
    • Unmanned Aerial Vehicle{ count++; Lcd8_Config(&PORTB,&PORTD,3,2,0,7,6,5,4,3,2,1,0); Lcd8_Cmd(LCD_CURSOR_OFF); INTCON.T0IE=0; INTCON.T0IF=0; SPBRG = 25; TXSTA = 0x00; RCSTA = 0x90; PIR1 = 0x00; PIE1 = 0x20;}if (PIR1.RCIF==1){ if ((RCSTA.FERR==1)&&(RCSTA.OERR==1)) //ferr & oerr { RCSTA.CREN=0; outar[l]=RCREG; l++; outar[l]=RCREG; discard=1; if ((outar[l-1]==0x0D)||(outar[l]==0x0A)) gflag=1; else if((outar[l-1]==$)||(outar[l]==P)) l=0; else l++; RCSTA.CREN=1; } else if ((RCSTA.FERR==1)&&(RCSTA.OERR==0)) //ferr only { discard=1; outar[l]=RCREG; if ((outar[l-1]==0x0D)||(outar[l]==0x0A)) gflag=1; else if((outar[l-1]==$)&&(l>1)) l=0; else l++; } else if ((RCSTA.FERR==0)&&(RCSTA.OERR==1)) //oerr only { RCSTA.CREN=0; outar[l]=RCREG; l++; outar[l]=RCREG; if((outar[l-1]==$)&&(l>1)) {discard=0; outar[0]=$; outar[1]=P;l=2;} if (outar[l]==0x0A) gflag=1; //gflag=1 msg done from 0-L else l++; RCSTA.CREN=1; } else if((RCSTA.FERR!=1)&&(RCSTA.OERR!=1)) //byte finished { outar[l]=RCREG; Page 162
    • Unmanned Aerial Vehicle if((outar[l]==$)&&(l>0)) {discard=0; outar[0]=$; l=1;} if (outar[l]==0x0A) gflag=1; else l++;}if((gflag==1)&&(discard==0)){ if (outar[18]!=A) discard=1; else if(outar[18]==A) { gflag=0; for(i=1;i<=l-5;i++) //crc checker check^=outar[i]; //check crc if valid start flight if (outar[l-3]>=A) crc1=outar[l-3]-A+10; else crc1=outar[l-3]-0; if (outar[l-2]>=A) crc2=outar[l-2]-A+10; else crc2=outar[l-2]-0; crc=(crc1<<4)+crc2; glat=(outar[25]/10)+(outar[26]/100)+(outar[27]/1000)+(outar[28]/10000); glong=(outar[38]/10)+(outar[39]/100)+(outar[40]/1000)+(outar[41]/10000); l=0; if (outar[49]==,) { gvel=outar[48]*(10*outar[47])+(100*outar[45]); if (outar[54]==,) ghead=(10*outar[50])+outar[52]; else if(outar[55]==,) ghead=(100*outar[50])+(10*outar[51])+outar[53]; else if (outar[56]==,) ghead=(1000*outar[50])+(100*outar[51])+(10*outar[52])+outar[54]; } if (outar[50]==,) { gvel=outar[49]*(10*outar[48])+(100*outar[46])+(1000*outar[45]); if (outar[54]==,) ghead=(10*outar[51])+outar[53]; else if(outar[55]==,) ghead=(100*outar[51])+(10*outar[52])+outar[54]; else if (outar[56]==,) ghead=(1000*outar[51])+(100*outar[52])+(10*outar[53])+outar[55]; } Lcd8_Out(1,1,work); Page 163
    • Unmanned Aerial Vehicle } } else if((discard==1)&&(gflag==1)) { l=0; discard=0; gflag=0; } PIR1.RCIF = 0; PIR1.RCIE = 0; PIR1.RCIE = 1; RCSTA = 0x90; INTCON = 0xC0; } INTCON = 0xC0;} Page 164
    • Unmanned Aerial Vehicle APPENDIX C : WEIGHT & THRUST CHARTSWEIGHT CHART COMPONENT QUANTITY WEIGHT (g)1st Wood Chassis 1 197 nd2 Wood Chassis 1 933rd Wood Chassis 1 47.5Carbon-Fiber Chassis 1 43.5Battery (Li-Poly) 1 326Battery (9V) 1 35gMotor 4 284Sync 4 36Metal struts and screws 1 107Camera 1 63PIC 1 27Gyrometer 2 2Accelerometer 1 2RF transceiver 1 4GPS 1 15Ultrasonic sensor 5 30 The Brain PCB bare (old) 1 34Motor Driver with components (old) 4 68UAV (Config2) 1 1107gBrain(New) 1 190gUAV (All components, carbon-fiber) 1 990g Page 165
    • Unmanned Aerial Vehicle THRUST CHART GW/EPS-350C-CS Volts Amps Thrust EfficiencyPROPELLER Power (w) (V) (A) (g) (oz) (g/w) (oz/kw)EP1047 6 6.5 300 10.50 39.00 7.69 269EP1047 7.2 8.8 410 14.35 63.36 6.47 226EP1047 8.4 10.3 470 16.45 86.52 5.43 190EP1047 9.6 12.8 540 18.90 122.88 4.39 154 *Note: Last row shouldn t be tested, prolonged exposure to high voltage can irreversibly damage your motors. Page 166
    • Unmanned Aerial Vehicle APPENDIX D : LITHIUM POLYMER BATERY CARE Components involved with battery care include the following; Astro Flight 109Dlithium charger/discharger with dean s connectors, the 120 power supply rated at 13.5V,106 Blinky battery balancer, and the 549 blinky to thunder power adapter. The battery wasa thunder power model with dean s connectors, while some other batteries use an astroconnector. The 101D wattmeter with dean s connector is a useful tool to always know howmuch current the battery is releasing. Pictures of these products can be seen in section 4.4Major Components. All of these products were obtained from www.astroflight.com. Configuration is as follows, the power supply Vin connects regularly to a110V/220V source. Vout terminals connect to the Charger/Discharger with alligator clips.The Dean s connector of the charger connects to the dean s connector of the battery. Theblinky battery balancer connects to the adapter that connects to the balancer battery input. The two line display indicates the status of the charging sequence in six messagesshows (in order of left-right) shown in the figure below. Charge current (0.10A), number ofcells (2C), charge mode (2, following 2C in the second field), battery voltage (6.93V),charge duration (3:05:52), and number of milliamp hours of charge (0.26AH) to put intobattery pack. Page 167
    • Unmanned Aerial Vehicle For the first 3 minutes the battery will be charging in mode 1, even if the battery isfull, therefore do not charge a fully charged battery, it can overcharge and damage the cells.After those 3 minutes, the mode switches to 2. The charger has a current adjust knoblabeled Amps Adjust on the front panel (as shown in figure). Charging current can beadjusted from 50mA to 8A. Always start the current adjust at 0A and gradually increasecharging rate until the charge equals battery capacity (1C rate, at 1C the battery pack shouldcharge in 1 hour, charging at a higher rate can burn the battery). In this case that would be8A considering the battery is an 8000mA/hr pack. After a few minutes the charging currentdecreases slightly as the battery voltage rises, so raising the current can be done if desired.At 85% battery capacity the charger will switch to mode 3. In mode 3 charging current isturned on and off periodically until the resting voltage of each cell is 4.2V. When thecharger detects fully charged condition which is at 4.2V per cell (the battery is a 2 cell unitmeaning full charge is at 8.4V), charging stops automatically. The display will then indicatehighest resting voltage reached and number of mA/hr put into the battery since last charge. Caution should be taken to never let the battery drop below 3.2V per cell, thebattery pack should be disconnected and charged immediately. Should the voltage fallbelow that the battery should be charged at a rate between 5% and 10% of rated of cellrated mA/hr capacity. If the voltage falls below 2.5V per cell, the battery will sufferirreversible chemical damage, and will slowly and completely deteriorate in 30 days. Page 168
    • Unmanned Aerial Vehicle APPENDIX E: ICSP PROGRAMMING ICSP (In Circuit Serial Programming) allows developers to manufacture boardswith unprogrammed devices and program them while in the circuit. This is simply donewith two lines for CLK and DATA, and three other limes for POWER GND andprogramming voltage. Your programmer must support ICSP to use this function. The MCUmust have this option listed in its special features. The power line is connected to VDD theGND is connected to VSS the programming voltage is connected to the MCLR, the clock isconnected to RB6 and the DATA I/O is connected to RB7. Special attention must be paidto implement switches to isolate the circuit from the MCU during programming. Page 169
    • Unmanned Aerial Vehicle APPENDIX F: REFERENCESPrograms used in this project- PIC Simulator IDE v6.34 (Testing and simulating)- MP Lab v7.42 (PIC programmer)- EAGLE 4.16r1 (PCB Design)- Mikro Elektronicas MikroC (PIC code editor)- JCreator LE (Java Code editor)- WINPIC800 (PIC programmer)- SiRF Demo PC GPS Utility v3.83 (GPS initializer)- AutoCAD 2006 (Chassis drawings)- Google Earth (GPS aid)Datasheets & referenced websites- NMEA Reference Manualhttp://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual1.pdf- EM406 GPS Receiver Datasheetwww.sparkfun.com/datasheets/GPS/EM-406%20Product_Guide1.pdfADXL330 Accelerometer Datasheethttp://www.sparkfun.com/datasheets/Components/ADXL330_0.pdf- IDG300 Gyrometer Datasheethttp://www.sparkfun.com/datasheets/Components/IDG-300_Datasheet.pdf- 2SD1062 Transistor Datasheethttp://www.ortodoxism.ro/datasheets/mospec/2SD1062.pdf- Max Sonar EZ1 Ultrasonic Sensor Datasheethttp://www.maxbotix.com/uploads/MaxSonar-EZ1-Datasheet.pdf Page 170
    • Unmanned Aerial Vehicle- RF-24G Transceiver Datasheethttp://www.sparkfun.com/datasheets/RF/RF-24G_datasheet.pdf- nRF2401 Datasheethttp://www.sparkfun.com/datasheets/RF/nRF2401rev1_1.pdf- TIP120 Transistor Datasheethttp://www.ortodoxism.ro/datasheets/fairchild/TIP120.pdf- WS-309AS Camera Datasheethttp://www.nodactechnology.com/nuevo_sitio/catalog/images/docs/OCB-WS-309AS.pdf- PC817 Optocoupler Datasheethttp://www.ortodoxism.ro/datasheets/Sharp/mXqyrss.pdf- MikroC Manualhttp://www.mikroe.com/pdf/mikroc/mikroc_manual.pdf- 16F777, 16LF77 PIC s Datasheethttp://ww1.microchip.com/downloads/en/DeviceDoc/30498c.pdf-18F4431 PIC Datasheethttp://ww1.microchip.com/downloads/en/DeviceDoc/39616b.pdf-16F877, 16LF877 PIC s Datasheethttp://ww1.microchip.com/downloads/en/DeviceDoc/30292c.pdf-16F877A PIC Datasheethttp://ww1.microchip.com/downloads/en/DeviceDoc/39582b.pdf-74LS126A Quad Tri-State Buffer Datasheethttp://www.tranzistoare.ro/datasheets2/97/97398_1.pdf-HD447H0U LCD Datasheethttp://web.mit.edu/6.115/www/datasheets/44780.pdf Page 171
    • Unmanned Aerial Vehicle-2N2222 Transistor Datasheethttp://www.ortodoxism.ro/datasheets/MicroElectronics/mXrurvs.pdf-16/20 Key Encoder Datasheethttp://www.ortodoxism.ro/datasheets2/b/0dciii4xatog1g559sk4ahd595wy.pdf-Olimex Programmer Datasheethttp://www.olimex.com/dev/pdf/pic-mcp-c.pdf- Astro Flight Incwww.astroflight.comLatitude/Longitude tablehttp://home.online.no/~sigurdhu/Grid_1deg.htm Page 172
    • Unmanned Aerial Vehicle APPENDIX G : BIBLIOGRAPHYPID vs LQ Control techniques applied to an indoor micro quadrotorhttp://asl.epfl.ch/aslInternalWeb/ASL/publications/uploadedFiles/330.pdfDesign Of A Four Rotor Hovering Vehicleecommons.library.cornell.edu/bitstream/1813/93/2/Designof4RotHoverVehicle.pdfQuad-rotor Unmanned Aerial Vehiclehttp://www.me.columbia.edu/seniordesigns/2007/QUAVe/FinalReport.pdfGPS at Wikipedia.comhttp://en.wikipedia.org/wiki/Global_Positioning_SystemNMEA 0183 GPS Communication Protocolhttp://www.homebuilt.org/tech/nmea.htmlGWS-EPS-350C Motorshttp://www.gws.com.tw/english/product/powersystem/eps350c.htmGPS Timehttp://www.csgnetwork.com/gpstimeconv.htmlGPS Calendarhttp://www.ngs.noaa.gov/CORS/Gpscal.html Page 173
    • Unmanned Aerial VehicleA PDF version of this documentation can be found at: www.APR2.tk Page 174