# Standalone quadrocopter from scratch: PID and rake

Most projects using copters rely on manual remote control; there are no fully autonomous systems yet. But for industrial use it is necessary; the human factor is the cause of most accidents. Below, the story will go about how we made our stabilization system using PID , which minimizes human participation in the process of the drone.

One of the test flights of our copter.

When creating robots that are autonomous at a high behavioral level, one must work with all lower levels of autonomy, starting from stabilization in a given position. Therefore, we started by creating our own stabilization board.

Definition of autonomy
Autonomy is determined relative to the task. If the task is for the robot to follow the GPS coordinates initially set (for example, going around obstacles in its path), then by autonomy we mean the robot makes independent decisions from the moment it receives the route and the task. Autonomy at a higher level is, for example, an independent route choice when “patrolling” a certain territory. The initial data will be information about this territory.

#### PID

The simplest stabilization task is to control the angle of inclination, but it follows from the laws of dynamics of rotational motion that only its second derivative can be directly controlled. The easiest way to influence the desired value is to use PID.

MEMS  - in our case, it is a gyroscope, accelerometer and magnetometer; DMP - Digital Motion Processor; ESC  - controller of speed of brushless motors.

The generalized coordinate (in our case, the angle) is fed to the input of the controller, at the output we get the moment of forces (second derivative of the angle). Each PID controller stabilizes the value of one generalized coordinate . We use three PIDs with constant coefficients, one for each Taita-Brian angle.

#### Materiel

Define the discrepancy - the difference between the required and the real value of a certain value:

- the required value of the quantity (angle from the joystick),
- the current value of the quantity (angle from the sensor).

We set the moment of forces for the angle at the current time:

where  is proportional,  is integral,  is differential components.
The minus sign indicates that for positive , , the impact is directed against the rejection.

What is the meaning of this formula? We write the equation of dynamics by setting .

- moment of inertia.

For simplicity, we remove the integral component ( ). After re-designating the coefficients, we obtain the equation of damped oscillations relative to :

Where

That is, the larger the proportional component, the more “sharp” will be the reaction to the impact (the larger the amplitude). The larger the differential component, the faster the attenuation will occur (the greater the decrement).

From the model of damped oscillations, we obtain the expression for the damping coefficient:

Of the possible solutions to the equation, a regime close to critical (the aperiodicity boundary, ) is suitable for us - there is no negative “flight” of the graph, the transition process is short. As you can see, the critical mode is set by only one ratio to the coefficients of the PID controller.

The integral component eliminates the static error. Although the discrepancy is small and constant, then the differential component is zero, and the proportional component can be so small that the ESC accuracy is not enough to take it into account. In this case, the copter will not tend to the desired position. But if we summarize small deviations , then after some finite time the total deviation will be enough to compensate for the static error. Coefficientthis time determines: the larger the coefficient value, the earlier the system begins to take into account the growing error. In this case, too large an integral component leads to self-oscillations.

A more detailed analysis of the PID controller equation can be found in other articles: one , two .

#### First accident

Too large a differential component in practice leads to self-oscillations, which should not be in theory. Why? We remove all components except the differential one and solve the equation:

- exponent, no fluctuations!

The reason for this effect is a long reaction time of the system (and generally because it is nonzero). Due to a phase shift caused by a system delay, the function argument takes a certain decrement:

i.e., the quantity turns into a linear combination and its derivative. The same thing happens with the moment of forces, which is also a harmonic function in this example. For certain coefficients of the linear combination, they can be such that undamped self-oscillations occur.

Also, the result of the operation of the components of the PID must be limited modulo. Otherwise, the value , for example, will increase to overflow. There is also a problem with the other two components: it is necessary to achieve a quick reaction to external influence in the vicinity of the given position. For this, the coefficients should not be too small. But with large deviations (which are also possible in flight), large coefficients will lead to large-amplitude self-oscillations.

A compromise is the installation of not too small coefficients in conjunction with the introduction of a restriction from above on all three components: proportional, integral and differential.

It is worth saying that the real correction in an almost horizontal position is about 1–2 parrots per cent of the motor power (flight power is about 60%).

Consider the solution of the second-order equation (1), which in one of the cases is a damped sinusoid.

In practice, it really turns out something similar (example on the right). For demonstration, the coefficients are specially degraded to increase the decay time. The original ESC firmware had to be replaced, because it introduced a significant delay, due to which the mathematical model poorly described the real system.

Because the- the component is proportional to the angular velocity, one may come to the idea of ​​applying gyroscope readings to the input of the regulator instead of applying a discrete difference scheme. In this case, it is important not to forget to add to the input the derivative of the required angle from the remote control, without this, the control will be slow. The graph on the left shows how important the differential component is in control.

#### PID calibration

By the behavior of the system (real-time graphs of the components), it is possible to evaluate which coefficient leads to the occurrence of an undesirable effect. Therefore, they can be easily picked up manually (or guessed), for which we used a stand with a flexible suspension.

For corners , we hung it by the opposite axis under test, and for the corner we used 4 ropes symmetrically mounted on the frame near its center.

Although this approach is not the most effective (we do not know the “expiration date” of the coefficients quantitatively and consider them to be constants), in practice, we solved the problem of stabilizing a copter in flight. True, there was a problem with management, but more on that later.

Values ​​on which the behavior of the apparatus depends
We have received experimental confirmation that the coefficients of the PID controller depend significantly on the internal factors of the system. In the future, it makes sense to conduct a series of experiments to identify the dependence of the coefficients on the following factors.
##### Intrinsic factors
 Propeller Parameters (Diameter X Pitch) The larger the propellers, the smoother the copter's behavior. Copter dimensions (distance between the center of the frame and the axes of the motors) The larger the dimensions, the smoother the behavior of the copter Weight of fully equipped copter The higher the mass, the smoother the copter's behavior. Battery Charge (Voltage) The higher the charge, the more dynamic the behavior is potentially achievable for the copter

##### External factors
 Air temperature The warmer the air, the lower the density. As a result, smoothness increases. Atmosphere pressure The greater the pressure, the higher the density. As a result, smoothness decreases. Relative humidity The higher the humidity, the higher the water vapor pressure (and air density). As a result, smoothness decreases. Wind power in terms of model The PID term is directly proportional to the constant component of the wind force. The variable component of the wind forces affects the - and - components

#### Rake

In the case of adjusting the power of motors, it is necessary to prevent too low and too high powers at which stabilization does not work correctly.

On the one hand, there is minimal power that cannot be reduced, or the motors just stop. On the other hand, a decrease in power may be necessary for the algorithm to work properly. If the power (throttle) is reduced too much, the PID can “roll off” to the bottom. To solve this problem, we limit the power available to the pilot.

Another hazard is the effect of spurious vibrations from motors on- component. They generate noise in the controller and lead to self-oscillations. We have limited the absolute angular velocity from below: the software filter resets all angular velocity values ​​below the threshold. But the problem did not completely disappear; now we are thinking of a more suitable solution.

The third pitfall is that using the integral PID term can interfere with takeoff from an incline. Componentaccumulates even before take-off, and already in the air the device experiences a bias in the opposite direction. Only after a couple of seconds, during which the copter manages to gain a significant linear speed, the integral component decreases to values ​​acceptable for flight. To solve this problem, you can turn on the integral component only after the thrust of the motors reaches a takeoff value (about 50% of the maximum), while the copter is already torn off the ground.

#### Software

The figure shows a simplified block diagram of a program executed on a stabilization board controller. The main part is the cycle. If at least one action in it is not performed on time, the frequency ceases to be constant, and stabilization does not work correctly.

As a dynamic sensor, we used the MPU-6050 because of its computing capabilities. The integrated processor (DMP) is able to partially process the data from the sensors, which allows you to offload the central controller. But it turned out that there are no reliable libraries for working with this device under Arduino. Jrowberg's solutionled to problems when used on a heavily loaded microcontroller. The code in the example relies on the synchronization of data reading. The FIFO buffer of the sensor, into which the calculated values ​​are written, is full in case of untimely reading. Since the first element is always read from the FIFO, when partially filled, a delay appears between the placement of new data in FIFO and its processing on Arduino. In turn, this delay leads to self-oscillations. When the buffer overflows, you have to clear the buffer: its size is 1024, which is not divided by 42 - the packet size. Therefore, when the buffer overflows, at the beginning of the FIFO is part of some extraneous packet. In other words, starting from a certain moment, the structure is broken: the beginning of the FIFO does not coincide with the beginning of the packet, and it is impossible to read the correct data.

In addition, it was necessary to change the formula in the library for the transformation “quaternion ↦ angles” so that the result was from the full range of angles. Details of this problem are described on the project tracker: https://github.com/it-workshop/Quadrocopter/issues/18 .

#### On-board electronics

The main component that we developed independently is the stabilization board. Initially, it was based on the Arduino Uno platform, then it was replaced by a more powerful Due, which made it possible to increase the frequency of PID controllers from 40 Hz to 66. (6) Hz.

The propellers of the copter are driven by compact brushless motors in conjunction with standard speed controllers - ESC. We use ESC with modified firmware.

More on ESC
The ESC controller standard uses a meander as a control signal, and the duty cycle is a control parameter. In our case, the signal from the remote control initially receives the stabilization controller, which at the output is forced to generate the signal required for ESC. If you abandon such an interface (PWM), because of which you have to convert additional data, you can reduce the response time of the system. But designing your own engine controller is a separate task that we have not yet considered.

A lithium polymer battery (3S) is used to power the entire system. For security reasons, we decided to make a battery voltage monitoring system. In the normal mode of using batteries, the system behaves quite stably. However, at the initial stages of the work, we observed effects caused by suboptimal use of batteries:
• Swollen batteries. The reason is overcharging and long-term storage of discharged batteries. Manufacturers recommend not discharging power batteries below the value of 3.3V for each bank of the battery, which in our case gives the minimum allowable voltage of 9.9V.
• Shutdown motors at low voltage. This is a feature of the reaction of most ESC firmware to low voltage, which can lead to a serious accident - at the first moment only one motor is turned off, the rest continue to work.

For our purposes, it was decided to reprogram ESC. Thanks to the use of tgy firmware (from SimonK), we have achieved a reduction in system latency on the way from the central controller to the engines. As a result, the PID components and angular velocity became more sinusoidal, and the behavior of the entire system approached the behavior of the mathematical model.

The following sensors are used to measure dynamic parameters:
• InvenSense MPU-6050 6-axis accelerometer gyroscope
• 3-axis compass Honeywell HMC5883L

#### Telemetry

Remote control is implemented in two modes (to provide a more flexible development process):
1. Using xBee Pro modules in a PC copter configuration.
2. Using the allocated radio frequency (2.4 GHz) in the configuration “remote control ↦ copter”.

In addition to control via the remote control, critical data is sent between the copter and the PC in real time, for which xBee Pro and a proprietary application are used (see screenshot). On the computer you can see the value of angles and angular velocity, voltage on the battery, engine power. It is possible to adjust PID coefficients in real time. The program saves all incoming data and supports subsequent playback of recorded files, which helps with debugging. In the event of an emergency, we can stop the motors from the computer.

Data sent between the copter and the PC:
• PC ↦ Copter: control channel (PC / remote control), motor power, setting to enable / disable stabilization, PID coefficients and limits;
• Copter ↦ PC: angles, angular velocity components , , , joystick data (output angle + 3), motor power, the voltage on the battery.

Thanks to the sensor from InvenSense, the initial processing of data from the sensors takes place on the integrated processor (DMP). We unload the stabilization board, which can use even a low-power AVR microcontroller as a calculator.

##### Reproducibility of results

To create such a device, you need to assemble a similar mechanical structure, an equivalent electronic circuit and use our software.

The design of the frame greatly affects the flight performance. Having experimented with the materials, we came to the following.
• The foam frame allows you to build an extremely lightweight, but not rigid system. The copter has a significant windage. From this material it makes sense to make small systems (microcopters) that will fly indoors.
• A plywood truss frame is the least successful solution. A lot of assembly time due to the large number of small parts. The rigidity of the system can be ensured by additional sizing of the frame nodes, but then it becomes non-separable. The reliable frame is massive and has a noticeable windage. The strength is low, usually after a hard fit you need to glue cracked well or change the bearing parts. Of the advantages, it is worth noting the extremely low price.
• One of the most successful materials is aluminum. We used the popular X-525 model. The rigidity is high enough, the frame can only be damaged as a result of a serious accident. Sailing and weight are optimally low. The disadvantage is an unrecoverable small play in the joints of the frame parts.
• Composite carbon fiber has extremely high strength at a fairly low density. We used the Talon model. Since carbon is extremely difficult to process without special equipment, it was necessary to order finished parts and use them without any modifications. Due to the fact that the connecting nodes in carbon frames are usually made of plastic or aluminum, joints are difficult to align at the joints, i.e., there are frequent problems when working with a round carbon profile: poor alignment of the engines and backlash at the connection points.

###### Parts List
Frame Talon1100 rub.1Hobbyking
Battery 3S, 11.1V475 rub1Hobbyking
Propellers 10x4.5, 10x4.5R150 rub4Toyhobby
Turnigy Brushless Motors330 rub4Hobbyking
Esc290 rub4Hobbyking
2.4GHz remote control, 4 channels, with receiver875 rub1Hobbyking
Arduino due2590 rub.1amperka.ru
Arduino Wireless Shield790 rub1amperka.ru
InvenSence 6050 Sensor2335 rub.1www.lawicel-shop.se
Digital Compass HMC5883L1290 RUB1amperka.ru
XBee Pro2290 rub.2amperka.ru
Antenna for xBee Pro704 rub2wifimag.ru
Total18523 rub.

#### Directions for development

• The process of testing the stabilization system can be simplified using a more advanced stand. The rope option is more of a one-time solution, a more rigid gimbal suspension with three degrees of freedom would be more suitable.
• There are techniques for automating the selection of PID controller coefficients. For example, based on a binary search (branch and bound method). In our project, the coefficients were selected manually.
• The PC application used for monitoring and control would be more convenient to use on a tablet computer. Plans to port the application to Android or iOS.

#### Summary

The main achievement is an excellent team of enthusiasts who are able to work on complex robotic projects. We believe that it is all about creativity, opportunities for self-realization, and invaluable practical experience, which is always lacking.

We have created a new stabilization system project for multicopter. Now we can pilot a quadrocopter in open space. External factors such as wind, rain, and snow are compensated automatically by the PID controller.

At the moment, we will improve what we have done and are developing new automation functions.

summer 2013.

winter 2014.

Spring 2014