0% found this document useful (0 votes)
95 views163 pages

Principles of Drone Design

This document serves as a comprehensive guide for designing and building multi-propeller copters, intended for an undergraduate audience with a background in calculus, mathematics, and basic programming. It covers various aspects of UAV design, including physical modeling, control systems, flight controllers, sensor calibration, and on-board computing, along with practical instructions for constructing a UAV. Additionally, it addresses legal considerations and regulations for operating UAVs, ensuring readers have a complete understanding of the necessary components and processes involved.

Uploaded by

Đạt Phan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views163 pages

Principles of Drone Design

This document serves as a comprehensive guide for designing and building multi-propeller copters, intended for an undergraduate audience with a background in calculus, mathematics, and basic programming. It covers various aspects of UAV design, including physical modeling, control systems, flight controllers, sensor calibration, and on-board computing, along with practical instructions for constructing a UAV. Additionally, it addresses legal considerations and regulations for operating UAVs, ensuring readers have a complete understanding of the necessary components and processes involved.

Uploaded by

Đạt Phan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

© 2021 Mauricio Andrada - All rights reserved

ISBN: 978-1-7366303-0-3
Introduction
Chapter 1 - Physical models
Objectives
Modeling physical systems
Quadcopter physical model
Example 1
Example 2
Summary
Problems
Chapter 2 - Concepts of control systems
Objectives
System diagrams
Proportional controller
Steady state (t -> ∞)
Exponential terms
Derivative controller
Integral controller
Summary
Problems
Chapter 3 - Flight controller and sensors
Objectives
Reference flight controller - Pixhawk
Software implementation of a PID
Core sensors
Accelerometer
Altimeter
Magnetometer (compass)
Hall effect [14]
Anisotropic magnetoresistance (AMR)
Gyroscope
GNSS+RTK
Physical interfaces
General
UART (Universal Asynchronous Receiver Transmitter)[29]
I2C (Inter-Integrated Circuit)
SPI (Serial Peripheral Interface)[31]
CAN (Controller Area Network)[30]
Device drivers
Code analysis (optional)
Supplemental sensors
Sonars
Lidars
Optical flow cameras
Infra-red
Summary
Problems
Chapter 4 - Copter tuning and calibration
Objectives
Accelerometer
Magnetometer (compass)
Gyroscope
Electronic Speed Controller (ESC)
About Oneshot protocol
PID controllers
Summary
Problems
Chapter 5 - On-board computing
Objectives
Extending the UAV functionality
Computer selection
Weight
Size
Voltage and current
Computing power
Memory and storage
Peripherals
On-board computer and flight controller interface - MAVLINK
Messages and commands
Messages
NAV and DO commands
Connecting to the flight controller
Message types
Flying the multi-propeller copter
Frames of reference and modes of operation
Core flight commands
Parameters and settings
Available libraries
Summary
Problems
Chapter 6 - Designing a multi-propeller copter
Objectives
Formulas and definitions
Payload and weight ratio
Thrust, power and motor specification
Battery
Electronic Speed Controller (ESC) current
Flight duration
Calculation procedure
Frame size
Battery position and arrangement
Battery holder or plate
Battery straps
Arms length
Legs
Head
Body
Foot
UAV Body
Propellers
Flight controller selection
Sensor tuning/calibration
PID tuning
Physical model
Closed-loop system with proportional controller
Resolve the equation
Apply constraints and calculate K
Parameters
MAVLINK
Serial ports
Multicopter position control
PWM outputs
Sensor position
Additional components
GNSS antenna/receiver
Real-Time Kinematics (RTK) board
Radio control receiver
Cellular modem
USB powered hub
Voltage regulators
Power distribution
5V distribution
Battery connectors
Battery charger
Power module
Power cables
Summary
Problems
Chapter 7 - Command and control software
Objectives
Software description
Setup
Chapter 8 - UAV Project
Objectives
Process
Weight estimate
Propeller and motor parameters
Propeller selection
Motor selection
Frame dimensions and materials
Landing gear/legs
Wiring
Bill of materials
UAV components
Other materials and tools
Blueprint and instructions
Instructions
Work area
Preparation
ESC configuration
Step 1: Download the BLHeli Suite
Step 2: Connect the ESC, programmer and PC
Step 3: ESC flashing and programming
ESC connection to motors
Mounting motors and ESCs
Step 1: Label the motor wires and ESC taps
Step 2: Mount the foldable joints
Step 3: Mount the motors and arms
Step 4: Mount the ESCs
Mounting and connecting batteries and power
Mounting and connecting remaining components
Calibration and configuration
Testing the configuration
Attaching propellers and flight
Chapter 9 - Final considerations
Objectives
Rules and regulations
14 CFR Part 107 - SMALL UNMANNED AIRCRAFT SYSTEMS
Remote pilot certification
Aircraft registration
Waivers
Remote ID
Limitations of using the mobile network
References
Appendix
A - Linearization
B - MAVLINK generated libraries
C language
Folder content
minimal/mavlink_msg_protocol_version.h
Java
Folder content
Messages
common
C - Radio controller setup (PX4/Pixhawk 4)
Smart-Bus protocol (S-BUS)
S-BUS cable
Telemetry data (optional)
D - GroundControl communication link setup
E - Propeller thrust and power calculation - momentum method
F - Raspberry Pi 4 serial port configuration
Pin address
Configuring the primary UART for use with Pixhawk
Configuring a secondary serial port
G - Launching an app on startup on RPi 4
Introduction
This book started as a textbook for the EET-112 Sensors for Drones
class at Union Community College; along the course, it evolved into a guide
for designing drones, specifically multi-propeller copters.
This book is intended to be a practical manual; any theoretical
material presented here is used as background to justify the calculations and
design presented in the final chapters; it would be difficult to understand the
numbers and design decisions without this foundation.
Since it is an undergraduate, college level work, the text does require
some knowledge of Calculus and Mathematics in general; some parts will
require understanding of software programming and a basic knowledge of
electricity and physics.
The mathematics will be kept quite informal, it is just a tool for
understanding some of the concepts presented along the book. The same can
be said for the physical models used throughout the text.
The content tries to aggregate in one single place all the information
needed to design and build multi-propeller copters - information that is
scattered all over the Internet - as well as data our team gathered from the
years spent building and flying custom made, mobile network connected
drones; some of the information in this book will not be found anywhere else;
this is, however, a rapidly evolving field and some of the information and
links here may become obsolete. As the author, I will try my best to keep the
information up-to-date.
This book is only published in electronic format; it contains links to
both online reference material and auxiliary files that complement its content.
Although readers can, in principle, obtain a printed copy, it will not be as
useful as the electronic version.
Chapter 1 will present key mathematical concepts used when
modeling physical systems. Physical models are the starting point for all the
calculations associated with UAV design. It will then cover the concept of
automatic control using PID controllers and its implementation.
Chapter 2 introduces the concepts and mathematics of control
systems, including system diagrams, open and closed loop systems and PID
controllers.
Chapter 3 introduces the flight controller as the core unit responsible
for allowing controlled flight of the UAV by implementing the controllers
studied in . The chapter then introduces sensors, the functional components
responsible for providing measurements used by the PID controllers.
Chapter 4 focuses on tuning and calibration of the core sensors used
for flight control, as well as the parameters that must be manually configured
by the user in order to guarantee safe, controlled flight.
Chapter 5 introduces the on-board computer, used for extending the
UAV functionality beyond flight. It will describe how the on-board computer
communicates with the flight controller as well as the network.
Chapter 6 covers the practical use of the concepts covered by the
previous chapters, introducing a systematic procedure for calculating the
dimensions of all essential parts of an UAV.
Chapter 7 presents a reference client/server application that allows
controlling the UAV over the mobile network using ground control system
software.
Chapter 8 presents the full design of an UAV, including costs, bill of
materials, blueprints and instructions on how to install and configure each
component. Although intended to be used as an educational tool, this design
can be used by the reader to build a fully operational UAV.
Chapter 9 covers some use cases and legal aspects of flying and
operating a UAV, including the latest regulation published by FAA,
certification requirements and rules related to flight beyond line of sight
(BLOS). The chapter also covers the limitations associated with using the
mobile network for command and control of remote UAVs.
Chapter 1 - Physical models
Objectives
This chapter the reader will learn:
● The concept of physical models
● The physical model for for the forces acting in a quadcopter
● System diagrams and concepts of system control
● The concept of proportional, integral and derivative (PID) controllers

Modeling physical systems


When it comes to control systems, the first thing needed is creating a
model of the physical system. It is imperative that it is understood how the
system behaves when an input is applied, if the system is to be controlled..
Physical models can be as approximate or as precise as needed; for
example, nonlinear systems that are difficult to analyze can, under certain
conditions, be made linear within a limited range of values for the variable
of interest.
Physical models are, in general, described using mathematical
equations. In particular, it is prevalent to model physical systems using
differential equations; the solutions of these equations will provide the
behavior of the system under specific boundary conditions.
Differential equations, however, are tricky: it is not always easy to
find an analytical solution for one; nonlinear differential equations are
particularly difficult to resolve.
When faced with a nonlinear equation for a system model, a common
approach is to find a linear system that approximates the system’s behavior in
the region of interest.
Here is an example: calculating the period of a simple pendulum.

Figure 1: Forces diagram in a simple pendulum


(Source: https://commons.wikimedia.org/wiki/File:Forces_acting_on_a_simple_pendulum.svg
Credit: MikeRun, License: CC BY-SA 4.0, via Wikimedia Commons)

Figure 1 shows the forces applied to the mass at the end of the string
in the simple pendulum.
Using Newton’s Second Law of Motion and relationships between
angular and linear velocity in a circular trajectory one can write the
following equation describing the motion of the pendulum:

(1.1)
In this model the inputs are the forces acting on the mass at the end of
the string.
This equation is nonlinear because the sine is a function of the variable of
interest and it is a nonlinear function. The analytical solution for this
nonlinear equation is complicated [1]
This equation is a mathematical model for the behavior of the simple
pendulum. Difficult as it is to resolve it in this form, it is still a simplified
model; many assumptions are implied in this formula:
1. The string’s length (l) is assumed to stay constant under tension; in reality
the string may change length while the pendulum swings and forces
change, due to elastic properties
2. This string is assumed massless with all the mass in the system
concentrated at the weight at the end of the string; in reality that is not true
3. Gravity’s acceleration (g) is additionally assumed to be constant but it
does have a small variation as the pendulum changes its height
4. Air resistance, the friction at the end of the string, Coriolis effects
associated with Earth’s rotation, etc. were not included
Moreover, more simplifications are necessary to eliminate the no-
linearity; if the angle of oscillation is sufficiently small then:

(1.2)
Replacing (1.2) in (1.1) the much simpler linear differential equation
is obtained:

(1.3)
The general solution for this equation is:

Assuming the following initial conditions for t = 0:

Then the solution for this differential equation is:

(1.4)
where:
θ0 = initial, sufficiently small angle (rad)

ω= = angular velocity (rad/s)


So, in summary:
1. Physical models are mathematical tools that approximately
describe the behavior of real systems and events
2. The complexity of a model depends mostly on the precision and
accuracy needed for predictions and calculations; in the simple
pendulum case, several effects were left out because they have
negligible influence in the result; if, however, a spring was used
instead of a string, then definitely the elastic forces would have to
be included in the calculation, since they would no longer be
negligible
3. If calculations result in a nonlinear model, try to linearize it by
limiting the range for the values of the variable of interest [2]
4. Determining what is relevant and what is not to a model may be a
trial and error process and may involve experimentation to verify
if the predictions made by the mathematical model do match reality
to the level of precision required.

In the next section, physical models for a quad copter drone will be
derived following the same strategies described in this section.

Quadcopter physical model


Let us apply the concepts from the previous section and try to derive
a few models for the quadcopter, based on different variables of interest.
Our goal is to describe the quadcopter using differential equations
that approximate the aircraft's behavior well enough to make predictions
about its characteristics, under certain conditions and constraints.
The forces and angular momenta applied to the drone will be used as
the input in the same way it was done with the pendulum.
Differential equations for altitude, horizontal speed and yaw will be
derived and analyzed.
Figure 2: Quad-copter basic diagram
Figure 2 is a basic diagram for a quad-copter viewed from above.
The central blue square represents the drone’s body, the green triangles at 450
represent the arms and the circles represent the propellers; the red arrows
indicate the direction of rotation of each propeller.
Notice that the propellers have to be counter-rotating in order to
compensate for each other's angular momentum. Were they all spinning in the
same direction the copter would spin in the opposite direction due to angular
momentum conservation.
Another consideration is the position of the propellers relative to the
center of mass; as a rule, the center of mass must be below the plane of the
propellers so the copter tends to balance itself, like a pendulum, and
coincide with the geometric center of the drone; in other words, the motor-
propeller pairs must be positioned symmetrically.
Figure 3 is the profile view of the model drone, with a positive pitch
angle; the figure includes all the forces and momenta applied to the copter.
The force diagram below is used to derive the equations for the copter
model.

Figure 3: Copter profile with forces and momenta diagram; θ is the


copter's pitch angle
The forces applied to the copter are:

1. lift, provided by the propellers and denoted by the Fi forces


2. gravity, represented by the letter g
3. drag or air resistance, denoted by the forces proportional to the
square of the speed
4. angular momentum, represented by the L vector; will be 0 when
all motors are spinning with the same RPM

As it was discussed before, the variables of interest are heading,


altitude and horizontal speed.
Dot notation for time derivatives wll be used when convenient.

Altitude
From Newton’s Second Law the sum of all vertical forces must be
equal to the drone’s mass multiplied by the vertical acceleration so the
differential equation for the altitude is:

(1.5)
But since vy is the time derivative of the altitude then (1.5) can be
rewritten as after rearranging the terms:

(1.6)
Notice that this is a nonlinear equation due to the term with the square
of the vertical speed.

Horizontal velocity
Following the same principle, the non-linear equation for the
horizontal velocity is:

(1.7)

Heading
Before deriving the heading equation, it is important to define the
concept of heading. When it comes to flight it is important to distinguish
between heading and course over ground.
Heading is the direction the aircraft is pointing to; in other words,
once the front of the aircraft is defined, heading is the clockwise angle
between the main axis of the aircraft and the magnetic (or real) North.

Course over ground is the direction the aircraft is flying. Copters in


particular have very flexible flight capabilities, being able to fly forward,
backwards and sideways; therefore, it is possible for a copter to fly North
while pointing East. On the other hand, course and heading usually coincide
for fixed wing aircrafts.
The heading equation is related to the angular momentum of the
propellers and the vehicle itself so let us provide some definitions before the
equation is derived.
For the purposes of this analysis, angular momentum is defined as:
(1.8)
where:
I = moment of inertia
⍵ = angular speed.
Moment of inertia for a solid is the rotation equivalent of mass to
straight movement; it represents the resistance - or inertia - of the solid to the
torque trying to rotate it.
Differently from the mass though the moment of inertia depends on the
object's geometry; therefore it can be quite difficult to calculate for complex
objects; in this case it is usually experimentally measured using, for example,
a trifilar suspension system.
Angular momentum is a conserved quantity. In the case of the multi-
propeller copter, when the propellers are identical and counter-rotating at the
same angular velocity, the initial total angular momentum is 0 (zero); if
however the angular velocities are changed then the entire copter will start
spinning to keep total angular momentum zero.
The spin direction of the copter will depend on which propellers are
changed; it will always spin in a direction opposite to the dominant
propellers.
Based on these considerations the heading angle equation can be
written as:

(1.9)
where:
ID = drones’s total moment of inertia
𝛼 = drone’s heading angle
Ii = moment of inertia of each motor-propeller pairs
𝜔i = rotation speed of each motor-propeller pair

The different signs for the terms in ωi emphasize the fact that
propellers are counter-rotating
Here are some examples of how these equations can be used.
Example 1

Consider a pilot wants to keep the copter hovering in place at a


certain altitude; in this case two conditions must be met:
1. The horizontal speed (and consequently the horizontal
acceleration) must be 0
2. The vertical speed (and consequently the vertical acceleration)
must be 0

From equation (1.7) this means that the term on the left must be 0;
since it is known that the lift forces are not 0 by definition - the aircraft is
airborne after all - then the sine of the pitch must be 0 or, equivalent, the
pitch must be 00.
Similarly, from equation (1.6), all terms on the left are 0; since the
pitch angle is 0, the conclusion is that the combined forces of all motor-
propeller pairs must be equal to the UAV weight.
Example 2

Considering a pilot wants to fly the copter forward at a constant


speed, while maintaining altitude; in that case two conditions must be true:
1. The horizontal speed must be constant and set to the target speed vh
2. The vertical speed (and consequently the vertical acceleration)
must be 0

From condition 1 the horizontal acceleration is zero so equation (1.7)


becomes:

(1.10)
where:
vh = is the steady, constant horizontal velocity
𝜃 = pitch angle
Rearranging the terms of the equation:

(1.11)
Notice that the pitch can no longer be 0. Based on this equation alone
there is an infinite combination of lift forces and pitch angles that can achieve
the desired speed. Let’s now add the second constraint.
From equation (1.6) and Example 1 it is known that, for the aircraft to
maintain a constant altitude, the terms on the right of equation (1.6) must be
equal to the weight. Explicitly:

Rearranging the terms of the equation:

(1.12)
Equating (1.11) and (1.12) and rearranging:

(1.13)
Equations (1.11), (1.12) and (1.13) provide some interesting insights:
1. Equation (1.13) tells us that the higher the desired speed, the
higher the pitch; however, Equation (1.12) tells us a higher pitch
means a lower cosine; in other words, more thrust is required to
keep the altitude. Therefore, there is a well-defined maximum
speed attainable by the aircraft, limited by the maximum thrust that
can be provided by the motor-propeller pairs.
2. Equation (1.13) also tells us that the higher the total aircraft mass,
the lower the pitch required to reach the desired speed. This may
sound counterintuitive, but keep in mind the higher mass requires
higher vertical thrust so a smaller pitch is enough to redirect
enough thrust for the aircraft to move horizontally.

Summary
At this point it must be clear that:
1. Flying a multi-propeller copter requires simultaneously adjusting
the spin of multiple independent motors to obtain a desired effect
(yaw, fly horizontally, keep altitude, etc.)
2. Even something apparently as simple as flying a multi-propeller
copter at a constant speed and altitude requires manipulation of the
lift forces of each individual motor

It is evident that the effort needed to fly a multi-propeller copter by


manually controlling each motor individually is overwhelming; in the
following sections it will be demonstrated how control systems come into the
picture to make this task feasible.

Problems
1. Using the simplified model for the pendulum, show that the angular

velocity is
2. Explain, in layman terms, why the higher the total mass of UAV, the
lower the pitch angle for a desired speed.
3. Write and resolve the force ODE for a system comprised of a mass
M, a spring with elastic constant K and a shock absorber with
damping constant B.
Assume the following:

where:
FE = elastic force applied by the spring
FB = damping force applied by the shock absorber

and initial condition:


x(0) = a
x’(0) = 0
Use the WolframAlpha Online [36] to check your answer.
Chapter 2 - Concepts of control systems
Objectives
This chapter covers:
● System diagrams
● Open and closed loop systems
● Proportional, integral and derivative controllers (PID)

System diagrams
When designing a system, it is useful to represent the relationship between
its components using a system diagram.
System diagrams are just a graphical representation of the inputs, physical
models and outputs using block diagrams.
Figure 4 shows the simplest possible representation of a system.

Figure 4: Block diagram for a system


h(t) represents the differential equation that models the system; i(t) is the
input - in our case the lift forces - and o(t) is the output - in our case one of the
variables of interest.
A system like this is called an open-loop system; it gets its name from the
fact that no measurement is taken from the output in order to regulate the input.
Open-loop systems are normally systems that do not require regulation: once
the input is set the system will provide a steady output consistently. For example,
electric motors: once the input current is set the motor will produce a certain
power/torque consistently.
If however the system is built with an electric motor where the input is not
the current but the desired rpm or power or torque to be generated, then things get
interesting.
Even more interesting, what if the design requires the motor to reach the
desired rpm or power or torque within a certain time? What if the system is
naturally unstable, in the sense that the output grows indefinitely when the input is
applied, until the system either saturates or breaks down?
In order to answer these questions, the concept of closed-loop systems must
be introduced. In general, closed loop systems measure the output, compare it with
the setpoint and use that comparison to modify the actual input injected in the
system.
Figure 5 depicts the diagram of a simplified closed-loop system:

Figure 5: Simplified closed-loop diagram


Notice a few things from this diagram:
1. The input for the system is now the difference between input and output,
called error.
2. The input and output have the same dimension (e.g. speed) while in
Figure 4 the input could be, for example, lift forces and output could be
the altitude.

A particular structure for g(t) is a controlled system depicted in Figure 6:

Figure 6: Block diagram depicting g(t) individual components in a controlled


system
Figure 6 is simply the same diagram from Figure 5, but now with
equation g(t) split into its individual components: the original equation for the
physical model, h(t), and a new component k(e). This new component is
called controller and it has 2 jobs:
1. It converts the error - provided by e(t) - into the actual inputs for the
physical system For example, altitude error is converted into the lift to
be applied to the copter
2. k(e) is designed to produce i(t) in such a way that the output o(t)
reaches the desired value - called setpoint - according to the design
constraints (e.g. maximum error tolerance)

Clearly it must be possible to measure o(t), either directly or indirectly, in


order for the controller to work.
The topic of control systems design is quite extensive and outside of the
scope of this text; for a detailed description of control systems design techniques
and the mathematics involved see [4].
In the remainder of this chapter the powerful Proportional-Integral-
Derivative (PID) controller, extensively used in the flight controller, will be
studied. PID is a linear controller used in many different applications and is easy to
implement in software.

Proportional controller

Figure 7: Block diagram for the controlled model for altitude using
proportional controller
In order to make the calculations simpler, assume the multi-propeller copter
is flying vertically - therefore the pitch is 00 - and the total lift - FT(t) - is equally
distributed to all four motors. In addition assume the desired altitude is a constant
hD.
A linearized drag term is used in the differential equation to simplify the
calculations.
The proportional controller is the simplest controller that can be designed; it
simply multiplies the input by a constant K. The constant is known as the gain of the
controller.
Let us rewrite (1.6) with the simplifications defined in the previous section:
(1.14)
where:
cd = drag coefficient for linearized drag
FT = total lift

Let us define e(t) as:

where:
hD = desired altitude AGL

Per the system diagram, after applying the proportional controller:

where:
K = gain of the proportional controller
Finally, replacing this expression in (1.14) and rearranging the terms, the close-loop
equation of for the system is:

(1.15)

If the equation is carefully analyzed it is almost exactly like equation (1.6):


the terms on the right represent all the forces applied to the copter and the terms on
the left are the dynamic effects from the second law; the new term - Ky(t) - is the
controlling term.
Equation (1.15) is a second-order ODE (ordinary differential equation)
that can be resolved using standard methods for second-order ODE resolution [5].
To completely resolve this equation a set of boundary conditions must be
established. In this case, assume:
The homogeneous differential equation is:

The solutions for this type of equation are of the form:

where 𝜆 is a complex number.


Replacing the general solution in the homogeneous equation and resolving
for 𝜆:

Since there are two possible values for 𝜆, the general solution for the
homogeneous equation is:

(1.16)
For the complete solution all is needed is one solution for the non-
homogeneous equation.
The right hand side of the equation is a constant; therefore, the solution for
the non-homogeneous equation is:

Replacing this in (1.15) and remembering that the time derivatives of a


constant are 0:

The complete general solution for equation (1.15) is then:

(1.17)
Since the aircraft is assumed landed, the initial value for the AGL altitude is
0; in other words, . Replacing this condition in (1.17) results:

(1.18)
A couple of conclusions regarding the behavior of the altitude can be
derived from this general form of the solution for the altitude.

Steady state (t -> ∞)


By making the time large enough, the exponential terms vanish and all that
is left is the constant term. In other words:

This result is interesting in itself:


1. The copter will never reach the desired altitude; there will always be an
error in the final altitude
2. The error can be minimized by making K large, but can never be made 0.
This result makes intuitive sense intuitively; as the drone approaches the
desired altitude the lift applied to the motors - proportional to the
difference between current and desired altitude - will eventually be
small enough to equalize gravity's pull; at that point the drone stops going
up. If the difference did get to 0, no thrust would be provided to the
motors.
3. There is a minimum valid value for K; if it’s too small, the motors will
either not rotate or will stop at the hover thrust before the UAV even
takes off
4. This result is consistent with what is expected for the lift value when in
steady state:

Exponential terms
The second thing to be noticed are the exponential terms and their
dependency on K.
Depending on the value of K there are three possibilities for the value of the
exponents:

Condition 1:
Under this condition both terms in A and B vanish over time but the term in
B vanishes slower than A and is the dominant term.
The conclusion here is that a lower value for K guarantees a smooth
ascension to the drone, at the price of a longer time to reach steady-state and a final
altitude with a larger steady-state error.

Condition 2:
Under this condition both terms A and B vanish at the same rate; the rate
depends only on the drag coefficient and the mass and is independent of the gain; in
other words the time it takes for the UAV to reach steady-state doesn't depend on the
gain.
Substituting K in equation (1.17) and making time infinite, an expression for
the steady-state altitude can be written:

This is a curious result where the steady-state error depends only on the
aircraft characteristics (drag and weight).

Condition 3:

In this case the square root will produce a complex number of the form ejb.
From Euler's formula:

where:
j = imaginary unit
Applying this result to equation (1.17), ignoring the imaginary terms
(imaginary terms don’t have any physical meaning in this case) and taking into
account that results:

(1.19)
Finally, applying (1.18) to (1.19) and rearranging the terms results:
(1.20)
Equation (1.20) models the case where the altitude has an attenuated
oscillatory profile; the term inside the cosine is proportional to the natural
oscillation frequency of the system.
If K is made large enough so that the error becomes negligible and the term
in 4mK becomes much larger than the drag constant, (1.20) can be re-written as:

(1.21)
Equation (1.21) shows that the altitude can be temporarily higher than the
desired altitude at a certain point in time; all that is needed is for the cosine to turn
negative. The earlier this happens is when:

This result gives us 3 important insights:


1. The larger the value of K relative to the drone's mass, the faster the drone
will ascend to the desired altitude (and pass it)
2. The drone will always overshoot the desired altitude and oscillate
around it with smaller and smaller amplitude until it reaches steady-state;
the rate of attenuation is independent of the gain
3. The closed-loop drone with a proportional controller is stable when the
input is a constant; in other words, it will always reach a steady-state

In summary, proportional controllers are a simple way to control the output


if the input is a constant. It is always stable but there is a trade-off between steady-
state error and performance (defined as overshoot and oscillation).
In the next section a derivative controller is added to the system. Most of the
following calculations will re-use results from the previous section.

Derivative controller
Let’s start with re-drawing the block diagram and adding the derivative
controller. The derivative controller is added in parallel to the proportional
controller and its output is combined with the proportional controller output as the
multi-propeller copter input.
Figure 8: Block diagram for a proportional-derivative controller
The lift will then be given by:

where:
Kd = gain of the derivative controller

Replacing the input lift forces with the output of the controllers in Equation
(1.14) and rearranging the terms results:

Grouping the common terms:

(1.22)
This equation is identical to equation (1.15) with the only difference in the
constant multiplied to the time derivative of the altitude, which means all results
from the proportional controller can be reused, just replacing cd occurrences with
(cd+Kd).
From the steady-state analysis:
Clearly the derivative controller has no effect on the steady-state error. On
the other hand, replacing the constants in Equation (1.20) (attenuated oscillation
case) results:

(1.23)
Like with the proportional controller, if the cosine becomes negative, the
altitude may overshoot the setpoint; however, now the gain from the derivative
controller can be used as follows:
1. Increase the dampening effect, by increasing Kd; in other words, the
system can reach steady-state faster
2. At the same time, reduce the overshoot when compared to the
proportional controller
3. Control the time to reach the desired altitude

In conclusion, by combining the proportional and derivative controller it is


possible to control not only the lift to get to the desired altitude - within an arbitrary
acceptable error - but also the speed and profile of the ascension curve.
The next section covers the integral controller and its effects.

Integral controller
The same way as the derivative control, the integral control goes in parallel
to the other two controllers and it contributes to the physical system's input.
Figure 9: Block diagram for the proportional-derivative-integral controller
The lift will then be given by:

where:
Ki = gain of the integral controller
D = arbitrary constant, dependent on boundary conditions
Replacing in (1.14) and rearranging the terms:

(1.25)
This is called a linear integro-differential equation. This particular
equation is solved the same way an ODE is resolved, by finding the general
solution for the homogeneous equation and one solution for the non-homogeneous
equation, then applying boundary conditions to calculate the other factors.
The homogeneous equation is:
Just like before, the solution is in the form:

Replacing the general solution in the homogeneous equation results:

The analytical solution for a polynomial of degree 3 is ridiculously


complicated [6] and it is not needed for this analysis. Suffices to say that, in
general, this polynomial has 3 roots and the solution for the homogeneous equation
is:

Now let us find one solution for the non-homogeneous equation.

Substituting this equation in (1.25) and again remembering that derivatives


of constants are 0 results:

(1.26)
Therefore,

The complete solution for the altitude is then:

(1.27)
This is a quite important result. Assume the exponential terms all vanish
over time; in that case, the steady-state altitude is:

It must be clear that the steady-state error introduced by the proportional


controller is now gone. That is the main contribution of the integral controller to the
system: it eliminates the steady-state error.
However, as usual, there is a trade-off. Differently from what was seen with
the proportional and proportional-derivative controllers, in this particular case the
exponential terms are no longer guaranteed to have a negative real element and are
not guaranteed to vanish. Depending on how the values for the gains of each
controller are chosen, if any of the exponentials end up with a positive real part, the
system will become unstable and will end in catastrophic failure.
There are many different techniques to determine gains for each controller.
In general these techniques require some design constraint: maximum time to
steady-state, maximum overshoot, maximum oscillation frequency, maximum steady-
state error, etc.
If the system is too complex, software tools like MATLAB are required to
properly simulate and design the control system. Otherwise, they can be calculated
manually.

Summary
The controller that combines the proportional, integral and derivative
controls is called a PID controller [7].
In summary:

Proportional controllers use the difference between the setpoint and output to
control the system input; there’s always a steady-state error.

Derivative controllers improve dampening of any oscillatory behavior and
maximum overshoot but it does not help removing the steady-state error

Integral controllers remove any steady-state error but the gain must be
carefully calculated since it may cause the exponential terms to grow and
make the system unstable
The objective of control systems design is to use the physical models to
calculate suitable values for each controller gain. Once the gains are calculated, the
PID controller is expected to force the system to behave as desired.
There are several techniques to calculate the values for the gains, but they
are all based on a suitable physical model of the system to be controlled.
Finally, the gains calculated for a UAV with certain characteristics -
particularly drag and weight - most likely will not work for another model. In order
to re-use the same flight controller in different models, it is impractical to
implement the controllers in hardware; therefore, it must be clear now why flight
controllers rely on software implementation of such control systems.

Problems
1. Write and resolve the ODE for the horizontal speed of a UAV in a closed
loop proportional-integral control system. Assume the following:
Chapter 3 - Flight controller and sensors
Objectives
This chapter covers:
● A reference flight controller - Pixhawk
● How a PID is implemented in software
● How sensors measure variable of interest
● Study the physical interfaces exposed by the flight controller and device drivers to sensors

Reference flight controller - Pixhawk


At this point it must be evident that automatic control is essential for a controlled and safe flight
of a multi-propeller copter - and any drone for that matter.
Furthermore, it should be clear that the values for the gains associated with each controller type
depends on the characteristics of the vehicles: mass, shape and motors.
It is of course possible to design and build control systems using only hardware; this is common
for example in industrial plants where the characteristics of the system are well-defined and do not
change.
In the case of drones, however, this would be unfeasible. For example, the mass of a multi-
propeller copter used for package delivery can vary greatly depending on the payload weight; the shape
and size of the payload change the aerodynamics and drag of the aircraft; motors with different power
profiles require different gains for the controllers.
The solution is to implement the control systems using general hardware that can be mass-
produced and, therefore, be affordable, and software that can be configured for different drone
conditions and setups.
In the case of drones the system responsible for this is the flight controller. There are several
flight controllers in the market to choose from; some are specialized for racing, others are for general
use. There are proprietary, closed flight controllers and open source software/hardware ones.
This section focuses on a very popular open source software and hardware flight controller,
because it gives us the opportunity to study the basic design of such a device and understand how the
PID controller is implemented.
The flight controller is the Pixhawk 4 [8]. It is an open source hardware solution so anyone can
order the components and build one themselves.
Figure 10: Pixhawk 4
(Source: https://docs.px4.io/v1.9.0/assets/flight_controller/pixhawk4/pixhawk4_hero_upright.jpg
Credit: © PX4 Dev Team, License: CC BY 4.0, via Wikimedia Commons)
Figure 11: Pixhawk 4 connectors diagram
(Source: https://docs.px4.io/v1.9.0/assets/flight_controller/pixhawk4/pixhawk4-connectors.jpg
Credit: © PX4 Dev Team. License: CC BY 4.0, via Wikimedia Commons)

Pins in each connector are numbered from left to right, where PIN 1 is the leftmost pin in the
connector.
The reference software for the Pixhawk is the PX4[9]. The firmware is extensive and covers a
variety of vehicles besides copters (rovers, fixed-wing aircrafts, boats, etc.) as well as a long list of
external devices and sensors.
This chapter highlights two aspects of the software: 1) the code that implements the PID
controller; 2) the code that implements drivers for the peripheral and embedded devices
In the previous section it was stated that the PID controller in the multi-propeller copter is
responsible for varying the lift provided by the motors to accomplish a certain result for example,
ascending and hovering at a certain desired altitude. Figure 12 diagram depicts the way this is done in
practice.
Figure 12: Block diagram of a flight controller connected to ESCs (electronic speed controllers) and
motors in a multi-propeller copter
In Figure 12 each ESC - electronic speed controller - is connected to an output pair of pins in
the flight controller and connected to the power input of a motor. The flight controller provides to the
ESC the percentage of total voltage that must be applied to the motor and the ESC converts that into the
appropriate amount of power that it allows to go from the power supply to the motor, indirectly changing
the motor RPM and therefore the lift as described in Equation (10).
In the particular case of Pixhawk and PX4, PWM - pulse width modulation - ESCs are
commonly used along with brushless motors.

Software implementation of a PID


The implementation of a PID controller in software is relatively straightforward. The algorithm
implements the closed-loop system studied in the previous sections, using suitable gains for the system
in use, as depicted in the flow diagram in Figure 13:
Figure 13: Flowchart for the generic PID controller algorithm
Here is the implementation of a general PID controller in PX4:

/*
* Generic PID controller algorithm
* *pid: pointer to memory storing the previous values
* sp: set point or the desired value for the variable of interest
* val: current value for the variable of interest
* val_dot: first derivative for the variable of interest
* dt: time interval between calculations
* */
__EXPORT float pid_calculate(PID_t *pid, float sp, float val, float val_dot, float dt)
{
if (!PX4_ISFINITE(sp) || !PX4_ISFINITE(val) || !PX4_ISFINITE(val_dot) ||
!PX4_ISFINITE(dt)) {
return pid->last_output;
}
float i, d;
/* current error value */
float error = sp - val;
/* current error derivative */
if (pid->mode == PID_MODE_DERIVATIV_CALC) {
d = (error - pid->error_previous) / fmaxf(dt, pid->dt_min);
pid->error_previous = error;
} else if (pid->mode == PID_MODE_DERIVATIV_CALC_NO_SP) {
d = (-val - pid->error_previous) / fmaxf(dt, pid->dt_min);
pid->error_previous = -val;
} else if (pid->mode == PID_MODE_DERIVATIV_SET) {
d = -val_dot;
} else {
d = 0.0f;
}
if (!PX4_ISFINITE(d)) {
d = 0.0f;
}
/* calculate PD output */
float output = (error * pid->kp) + (d * pid->kd);
if (pid->ki > SIGMA) {
// Calculate the error integral and check for saturation
i = pid->integral + (error * dt);
/* check for saturation */
if (PX4_ISFINITE(i)) {
if ((pid->output_limit < SIGMA || (fabsf(output + (i * pid->ki)) <= pid->output_limit)) &&
fabsf(i) <= pid->integral_limit) {
/* not saturated, use new integral value */
pid->integral = i;
}
}
/* add I component to output */
output += pid->integral * pid->ki;
}
/* limit output */
if (PX4_ISFINITE(output)) {
if (pid->output_limit > SIGMA) {
if (output > pid->output_limit) {
output = pid->output_limit;
} else if (output < -pid->output_limit) {
output = -pid->output_limit;
}
}
pid->last_output = output;
}
return pid->last_output;
}

The output of the function is the throttle value to be applied to the motors (to be precise, the
percentage of the full throttle to be applied). This function is used by the main application running in the
PX4 to determine the power output to be applied to the motors, given a certain value for a variable of
interest.
Multiple instances of this type of controller, in different combinations and measuring different
variables of interest, can be used for all operations of a UAV: take-off, hover, landing, flying
horizontally, etc.
There are two important arguments as the input arguments for this function: the current value and
the first derivative of the variable of interest. Let's take a closer look at these for two variables of
interest that were studied earlier: horizontal speed and altitude.
Variable of interest: horizontal speed
If the variable of interest is horizontal speed, the software can provide two arguments: current
velocity (val) and current acceleration (val_dot); both can be measured directly and provided to the
controller.
Variable of interest: altitude
In this case the software can provide the current altitude (val) and, optionally, vertical or
ascension velocity (val_dot). In general only the current altitude is needed; it can be measured directly
and provided to the PID.
Notice that the algorithm requires measuring at least the current value of the variables of interest
and feeding those back into the loop; these variables are measured using sensors.
Sensors can be classified in two main categories: core and supplemental. Core sensors are
those essential for flying the aircraft; lacking one of them can drastically increase the risk of losing
control of the aircraft or even making controlled flight impossible.
Supplemental sensors are those that can be used for additional functionality (e.g. collision
avoidance) or as backup for a core sensor (e.g. position indoors when GPS is not available); they can
even provide extra accuracy to the core sensors when present.
The next section describes the core sensors, how they work and how they are used.

Core sensors
Core sensors are those sensors fundamental for both manual and autonomous flight. They are
used directly by the controllers within the flight controller, providing the current values for the variable
of interest and allowing the controllers to stabilize the aircraft during flight. These sensors are usually
built into the flight controller and are accessible via either SPI and I2C bus, although other buses can be
used.

Accelerometer
Accelerometers are used to measure acceleration. Accelerometers can come in a variety of
types: 1) gravimeters, used to measure gravity; 2) linear accelerometers, measure the vehicle's
acceleration without gravity; 3) pure accelerometers, measure the raw acceleration of the vehicle
including gravity.
Accelerometers used in drones must measure acceleration according to some predefined 3-D
coordinate system, usually relative to the device; it measures acceleration in directions x, y and z.
The flight controller must be mounted in such a way that the three axis assumed by the sensor are
aligned with the drone's axis: x points" to the "front” or the normal forward direction of flight of the
drone, y points to the "side" and z points "upwards".
Accelerometers as well as some of the other sensors will study here, use a technology called
MEMS - Micro Electro-Mechanical Systems[10] - which allows adding tiny mechanical systems that
interact with electrical circuitry.
Examples of MEMS technologies used in accelerometers are: 1) piezoelectric crystals, which
generate an electric charge when under a force; 2) thermal MEMS, which use variations in temperature
of a heated gas sealed in a chamber inside the chip[11]
Pixhawk 4 comes with two accelerometer/gyroscope combos: 1 x ICM-20689 and 1 x BMI055
in the IMU (Integrated Measurement Unit).
The acceleration measured by the accelerometer is one of the inputs to the PID controller when
controlling for example horizontal speed.
The Pixhawk 4 comes equipped with accelerometer/gyroscope combos, a ICM-20689 and a
BMI055.

Altimeter
Altitude is usually measured in two ways, depending on the application: 1) relative to the ground
(AGL); 2) relative to the mean sea level (AMSL)
Altitude is a fundamental measurement when it comes to flying drones. Drones are not allowed
to fly above 400 feet relative to the ground or a structure nearby and only in certain air spaces with
limited maximum altitudes[12].
Altitude can be measured in a few ways: 1) electronic air pressure sensors (barometric
altimeters); 2) GPS; 3) distance sensors (lidars, sonars)
Barometric altimeters in general use a piezoresistive component that changes electric resistance
with pressure. The chip has a pressurized chamber - the reference pressure - and a small inlet for the
external air to enter; the pressure difference between the external air pressure and the reference pressure
deforms the piezoresistive component, changing its resistance; the change in current allows for the chip
to measure the pressure difference and calculate the altitude.
Pixhawk 4 comes equipped with 1 x MS5611 in the IMU. This altimeter is a type of MEMS that
uses piezo-resistive components that change electric resistance depending on the applied pressure[13].
The current altitude measured by the altimeter is input to the PID controller.

Magnetometer (compass)
Magnetometers are used to determine the direction of the Earth’s magnetic field and,
consequently, the orientation of the aircraft relative to the Earth’s magnetic North.
Magnetometers are important for drone flight depending on the mode of operation. Symmetric
multi-propeller copters are quite flexible when it comes to flight, being able to fly in any direction while
never changing heading; if however the operation requires the drone to always fly along the heading or
that the drone is pointed to specific directions (e.g. when filming during flight) then compass becomes
important.
Magnetometers use different methods to determine the direction of the magnetic field.
Hall effect [14]
If one assembles a circuit in such a way that a well-defined electric current travels across a
metallic surface it is generally expected that the flow of electrons is uniformly distributed across the
whole surface and therefore the electric potential between the opposite sides of the surface will be zero.
However, if a magnetic field is applied to the surface, it will disturb the electron flow, causing it
to be skewed and concentrate in one of the sides of the metallic surface; that unbalanced distribution of
electrons generate a voltage between the opposite sides of the surface; this voltage can be measured and
used to calculate the magnetic field being applied.
Anisotropic magnetoresistance (AMR)
Certain materials change electric resistance depending on the angle of the magnetic field
applied to it.
By measuring the change in terminal voltage or current and calculating the resistance the device
can determine the angle of incidence of the magnetic field.
Pixhawk 4 comes with a IST8310 AMR magnetometer; however, using Pixhawk’s internal
compass alone is not recommended, due to the device's proximity to multiple sources of magnetic fields
(wires and other electronics). As it will be discussed later, the GPS receivers used with drones also
come equipped with a compass and it is highly recommended to also use this compass.
Gyroscope
Traditional mechanical gyroscopes are machines built in such a way that, when all the elements
are spinning, it does not matter how it is moved, the axis of the center spinning piece is always pointing
in the same direction. This happens due to the conservation of angular momentum.
Electro-mechanical gyroscopes can be used for very precise positioning. In three-dimensional
space, it is possible to determine the position of any point if one has the direction from that point to six
known reference points (it is the equivalent, 3-D space, of triangulation in 2-D space); hence, if an
aircraft has six gyros on board, pointing to six reference points, as the vehicle moves it measures the
angle of the spinning axis relative to the board and can precisely triangulate the vehicle position.
The technique was used in the Apollo program where the gyros pointed to known stars -
considered fixed points in space - and therefore the on-board computer could determine its position at
all times.
Another use for gyroscopes is measuring angular velocity; since the spin axis is always pointing
to the same direction as the vehicle moves, it can measure the angular velocity by measuring the angular
velocity of the spin axis relative to the board.
Electronic gyroscopes are used in that capacity.
Electronic gyros use a number of different techniques to measure angular speed: 1) ring laser
gyros use the frequency difference between 2 lasers sent into a circular route in opposite directions
when rotation is present, due to Dopler effect; 2) vibrating structure gyros uses a quartz crystal vibrating
at a very precise frequency; when rotation is present the crystal tends to continue vibrating in the same
plane (Coriolis effect) so the chip can measure the forces of the crystal on its support; etc.
The Pixhawk 4 comes equipped with accelerometer/gyroscope combos, a ICM-20689 and a
BMI055.

GNSS+RTK
Of all the sensors discussed here so far the GNSS receiver is the only core sensor that is external
to the flight controller.
There are several GNSS - Global Navigation Satellite System - systems: USA's GPS, Russia's
GLONASS, Europe's Galileo and China's BeiDou, among others.
GNSS receivers calculate their positions using the known position of some satellites in a
constellation and the travel time of a message from the satellite to the receiver (the travel time is the
difference between the time a message is received and the time it was sent; the send time is recorded in
the message, along with the satellite position).
Assuming the receiver's clock is not synchronized with the satellites' clocks, one can write the
equations for the receiver position as a system of equations as follows:
where:
c = speed of light
xi, yi, zi, ti = satellite i coordinates and time message was sent
x, y, z = unknown position of the receiver
treceiver = time at the receiver
terror = unknown error in the time measurement (lack of synchronization, atmospheric effects, etc.)

Since there are four unknowns, a minimum of four equations are needed in our system of
equations and therefore a minimum of four satellites; more satellites will help make the calculations
more accurate.
Pixhawk 4 and PX4 support several GNSS receivers using a variety of protocols. It is usual to
select a receiver that also has a compass but it is not mandatory.
GNSS position information is mostly used when the aircraft is flying autonomously executing a
mission; PX4 uses the data in a few ways:

1. Determine route to the target location from the current position


2. Determine if the flight path is deviating from the route and provide corrections
3. Determine if the target position is reached or is close and trigger decisions regarding the
flight plan (go to the next position, hover in place, etc.)

Position could theoretically be also used within a PID controller but in practice it's not; the logic
is usually very simple, by simply checking if the vehicle is within a certain radius of the target position
and using that condition to trigger the next step in the flight.
RTK (Real-Time Kinematic)[15] is a technique to improve the accuracy of GNSS-based
positioning. It uses a fixed base station at a known position that can measure errors in the location and
broadcast correction information to GNSS receivers within a certain range (around 6 miles); correction
data is commonly sent using NTRIP (Networked Transport of RTCM via Internet Protocol) where the
messages content and format are defined by RTCM (Radio Technical Commission for Maritime
Services)[16]. RTK can provide accuracies under 3 cm.
Now that our review of core sensors is completed, let’s look into supplemental sensors; but
before that it is important to take a look at the physical interfaces the Pixhawk offers for connecting these
supplemental sensors.

Physical interfaces
Pixhawk 4 offers a number of external physical interfaces that allow attaching peripherals and
sensors to expand both the functionality and safety of the drone.
General
Some of the interfaces about to be studied have one characteristic in common: all devices in the
bus share the same wire to send and receive data. Therefore, they all implement some mechanism that
allows one of the devices (e.g. a master device) to take control over the bus.
This is normally done by changing the voltage level in the wire to a level that is standardized and
agreed with the chipset manufacturers.
This is accomplished using a circuit like the one below:
As it can be seen, if no voltage is applied to the base of the transistor, the transistor is not
conducting any current between the collector and emitter and therefore the voltage in the line will be at
the "high" level.
Once a suitable voltage is applied to the base, the transistor conducts and the voltage drop in the
collector resistor causes the voltage to drop to the "low" level.
Observe that in this scheme the collector resistor is passively keeping the voltage high, simply
because no current is flowing through it; this type of state is called passive pull-up.
Conversely, the low level in the line is forcefully set by creating a current through the transistor;
this state is called active pull-down.
In general, if a port has an active pull-down it will have a passive pull-up and vice-versa.

UART (Universal Asynchronous Receiver Transmitter)[29]


UART is a serial physical interface used for one-to-one communication between 2 devices. It
requires just two wires connecting the devices and supports both full and half-duplex communication.
Data is transmitted using a structure with one start bit, 5 to 8 bits of data, one optional parity bit
and a stop bit (the width of the stop bit can be 1, 1.5 or 2 bits).
One of the advantages of UARTs is the synchronous data transmission; both sides can send data
at the pre-established baud rate without having to wait for a clock signal.
The main disadvantage of using UARTs is that all the parameters - baud rate, number of parity
and stop bits - must be preset before communication can start; there are however some chipsets that
support auto baud rate detection; the chip analyzes the structure of the incoming data to determine its
parameters but these are not used by Pixhawk.
Another disadvantage of UARTs is that it only allows 1-to-1 communication so one can only
connect one device to a UART port; if the design requires multiple components connected then other
interfaces must be used.
Pixhawk provides four UARTs using 3.3 volts for the port level. Some of these UARTs are
preassigned to specific functionalities as it will be explained later.

I2C (Inter-Integrated Circuit)


I2C was introduced in the 1980's by Philips Semiconductors as a bus allowing a CPU - central
processing unit - or MCU - microcontroller unit - to connect to its peripherals via a 2-wire
interface, reducing the amount of components needed using traditional access using parallel memory
address with memory decoders, chip enable signals and parallel data buses.
In order for this to work the I2C bus also introduces a protocol using a master-slave structure: the
CPU is the master and all peripherals are slaves. Each peripheral is pre-programmed with an address
that is used by the CPU to grant access to the bus to one peripheral at a time.
The main advantage of the I2C bus is the cost savings in components and easy connection of
multiple devices; the main disadvantage is its serial nature of communication which is slower than
traditional parallel memory read/write; the highest speed for I2C communication is 3.2 Mbits/s; normal
rate is around 100 kbits/s.
Another disadvantage is that I2C requires data to be sent in chunks of 8 bits, complicating usage
by applications that use different data structures.
One line of the bus is named SDA - serial data - and is used by the master to write/read data
to/from a peripheral. The other line is called SCL - serial clock - and is used by the master to indicate
when a bit of data can be placed in the SDA; it is also used, in combination with the SDA line, for the
master to indicate to all peripherals when communication is started and when it is stopped. Data can
only be written to the SDA line when the SCL is low and the SDA level cannot change while SCL is
high.
Devices use 7-bit addresses so in principle one could attach up to 128 devices to the line;
however due to the fact some addresses are served for special usage only 121 can be connected. When
connecting devices to the bus one must be aware of the capacitance added to the line by each peripheral,
since these can interfere with the signals and introduce communication errors.

Figure 14: I2C protocol


(Source: https://upload.wikimedia.org/wikipedia/commons/thumb/6/64/I2C_data_transfer.svg/600px-I2C_data_transfer.svg.png
Credit: Marcin Floryan License: public domain)

Peripheral addresses are usually programmed into the device using a mechanism provided by the
manufacturer; devices must be set with an address before they can be connected to the bus.
The protocol is defined as follows[17]:

1. The master indicates a communication start by making the SDA level low while the SCL is
high (start sequence)
2. The master writes the 7 bit for the device address then adds an 8th bit to indicate if it is a
write operation (low) - the master is sending data to the peripheral - or read operation
(high) - the master is reading data from the peripheral. Each bit of the address is written by
the master by lowering the SCL level, raising the SCL level for the clock pulse duration and
lowering it again.
3. Either the master or the peripheral writes data to the SDA, depending on the operation being
performed; the data must be written while the SCL line is low.
4. The master then pulses the SCL to indicate the operation is done. Once 1 byte is transmitted,
the receiver adds an ACK bit to indicate to the sender data is received and another byte can
be sent.
5. When the data transmission is finished, the master sends a stop sequence by making the SDA
line high while SCL is also high.
The amount of data to be sent by master and peripheral is peripheral-dependent and is controlled
by software; in the Pixhawk the communication protocol for each peripheral is implemented by device
drivers.
Some devices for example may provide access to registers that are individually addressable by
the master; in this case the protocol involves the master first doing a write procedure to provide the
register address to be used by the peripheral, a stop sequence then a new start sequence to actually
read/write data; the peripheral will "know" it is supposed to read/write from/to the register previously
set by the master.

SPI (Serial Peripheral Interface)[31]

Figure 15: SPI in 4-pin configuration


(Source:https://upload.wikimedia.org/wikipedia/commons/e/ed/SPI_single_slave.svg
Credit: en:User:Cburnett, License: CC BY-SA 3.0 , via Wikimedia Commons)

The SPI interface was developed by Motorola in the 1980s as a short-range communication
interface for peripherals like LCD displays.
Similar to the I2C interface, the SPI is a synchronous serial interface that uses a master-slave
architecture where the master is responsible for controlling the clock. However, it has several
differences when compared to I2C.
The main difference is that SPI allows for full-duplex communication; that comes with the price
of a more complex hardware that requires 2 wires for data (MOSI and MISO) and 1 wire for clock
(SCLK). If the system requires multiple SPI peripherals to share the bus - called 4-wire configuration -
then more hardware is required because SPI does not have an address system like I2C and uses a
traditional chip select signal granting the chip access to the bus.
The SPI specification defines a set of registers that allow configuring the SPI interface
functionality and work as buffers for data to be sent/received.
Among other features the registers allow configuring the character length (between 2 and 16 bits)
and the clock polarity and phase.

Polar Ph Description
ity ase
0 0 Output in the rising edge of clock; input latched in the falling edge
0 1 Output first half-cycle before first rising edge, then falling edge subsequent cycles; input
in the rising edge
1 0 Output in falling edge; input latched in rising edge
1 1 Output first half-cycle before first falling edge, then rising edge subsequent cycles; input
in the falling edge

Figure 16: Clock polarity and phase combinations


An simplistic way of thinking of the SPI is as a shift register: data is written in the buffer and
shifted bit by bit into the data line at every clock pulse.
Differently from the UART, the TX and RX are not fixed pins; the pin functionality depends
whether the chip is working as master or slave. MISO - master in, slave out - will work as input or
output depending if the chip is master or slave; conversely MOSI - master out, slave in - will behave as
output or input depending on the chip function.
Strictly speaking there are no formal SPI standards; the specification from Motorola is the de
facto standards; that however opens up for several variations on the implementation, including which
features are supported by a chip.

CAN (Controller Area Network)[30]


The CAN bus and protocol was developed by Bosch in the 80s to fulfill needs from the
automotive industry with first chipsets released in 1987 and first car with a CAN network in 1991; it
was standardized by ISO 11989 in 1993.
The main innovation provided by the CAN system when compared to other master-slave serial
buses is the multi-master architecture, which allows modules in the shared bus to get access to the data
line with no delay, thanks to the arbitration mechanism.
One secondary result of using CAN was the reduced wiring required to connect the electronics
in the vehicle, contributing to cost savings in production and maintenance.
The CAN specification makes no assumption on the physical nature of the bus; it can go from a
simple 2-wire bus to a sophisticated fiber optics system. Therefore, it defines two types of data bits:
"dominant" and "recessive", where "dominant" corresponds to the logical 0 and "recessive" to logical 1.
Because CAN does not have a centralized master, all data sent by any device is a broadcast
message with an identifier; any device in the bus can then consume the message if necessary.
Similarly, any device can request data from other devices in the bus; the device that "owns" the
message can then transmit it.

Figure 17: CAN data frame


Data transmission in CAN is asynchronous in the sense that there is no master clock controlling
access to the bus; however all devices must be synchronized so they can transmit and read the data from
the bus; synchronization is achieved by using transitions from "recessive" to "dominant" states.
Since there is no master clock to synchronize the nodes, a technique called bit-stuffing is used to
make sure nodes are synchronized. During normal data transmission, after 5 consecutive bits with the
same logical level, an extra bit with the complementary level is “stuffed” in the message; the level
transition allows nodes to re-synch their internal clocks. This "stuffed” bit is removed from the message,
by the node, before the data is sent to the application.
The start of frame (SOF) single bit marks the beginning of a frame, when set to “dominant”.
The arbitration field is composed of an 11-bit message identifier and the remote transmit
request (RTR) single bit. This bit is set to “dominant” by the transmitter when the message is a request
for information from another node.
Arbitration is done by bit-wise comparison of the message identifier field. If multiple devices
start transmitting simultaneously, the message with the first "dominant" bit wins; the moment a transmitter
tries to send a "recessive" bit, but detects a "dominant" state in the data line it stops transmitting. This
arbitration mechanism allows for data to be transmitted with no delay; the devices that could not
transmit will buffer the data for transmission after the current transmission is finished.
The control field is composed of an identifier extension (IDE) bit, used to indicate if this
message uses the 18-bit identifier extension, and a 4-bit data length code (DLC) field, used to indicate
the size of the data field - from 0 to 8 bytes.
The 16-bit cyclic redundancy check (CRC) field is used to detect transmission errors.
The acknowledge (ACK) single bit is set by the transmitter with a "recessive" bit while all
successful receivers set it to a "dominant" bit; if the transmitter detects a recessive bit in ACK it knows
the message was not successfully received by any node.
The 7-bit end of frame (EOF) field is a sequence of “recessive” bits that cancel bit-stuffing and
indicate the end of a frame; a dominant bit here indicates a stuffing error.
Finally, the 7-bit interframe space (IFS) allows enough time for the controller to move a
successfully received message to the message buffer.
CAN does not specify any type of security mechanism to prevent the bus from being tampered
with; encryption or any other security mechanism must be implemented at the application layer.

Device drivers
In the previous section it must have become clear that physical interfaces specifications only
define how data is sent and received; it makes no assumptions about the meaning of the data and its
content.
Therefore, for a specific device to be able to function using a certain physical interface it is
necessary to write software that allows data to be sent, received and interpreted.
There are two ways this can be accomplished: 1) each application interested in interfacing with
a certain device implements the code to do so or 2) the system provides a device driver that implements
such communication protocols.
The second approach is the standard way for communicating with physical interfaces, for a few
reasons:
1. Reusability: the device driver is implemented once and used by any application interested
in it. Also if there is an issue with the device driver code, there is only one source to fix.
2. Abstraction: by implementing a common interface, device drivers allow applications to
interact with any sensor the same way, without having to worry about the underlying details
of the physical communication interface and protocols.
3. Privilege separation: it is common for device drivers to require a higher privilege level
for accessing the hardware than the level needed by an application; by separating the
device driver from the application, the 2 components can run at their appropriate
privilege level.

Here is the device driver code for the I2C interface of the MS5611 barometric pressure sensor:

/****************************************************************************
*
* Copyright (c) 2013 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file ms5611_i2c.cpp
*
* I2C interface for MS5611
*/
#include "ms5611.h"
#define MS5611_ADDRESS_1 0x76 /* address select pins pulled high (PX4FMU
series v1.6+) */
#define MS5611_ADDRESS_2 0x77 /* address select pins pulled low (PX4FMU
prototypes) */

device::Device *MS5611_i2c_interface(ms5611::prom_u &prom_buf);


class MS5611_I2C : public device::I2C
{
public:
MS5611_I2C(uint8_t bus, ms5611::prom_u &prom_buf);
virtual ~MS5611_I2C() = default;
virtual int read(unsigned offset, void *data, unsigned count);
virtual int ioctl(unsigned operation, unsigned &arg);
protected:
virtual int probe();
private:
ms5611::prom_u &_prom;
int _probe_address(uint8_t address);
/**
* Send a reset command to the MS5611.
*
* This is required after any bus reset.
*/
int _reset();
/**
* Send a measure command to the MS5611.
*
* @param addr Which address to use for the measure operation.
*/
int _measure(unsigned addr);
/**
* Read the MS5611 PROM
*
* @return PX4_OK if the PROM reads successfully.
*/
int _read_prom();
};
device::Device *
MS5611_i2c_interface(ms5611::prom_u &prom_buf, uint8_t busnum)
{
return new MS5611_I2C(busnum, prom_buf);
}
MS5611_I2C::MS5611_I2C(uint8_t bus, ms5611::prom_u &prom) :
I2C("MS5611_I2C", nullptr, bus, 0, 400000),
_prom(prom)
{
}
int
MS5611_I2C::read(unsigned offset, void *data, unsigned count)
{
union _cvt {
uint8_t b[4];
uint32_t w;
} *cvt = (_cvt *)data;
uint8_t buf[3];
/* read the most recent measurement */
uint8_t cmd = 0;
int ret = transfer(&cmd, 1, &buf[0], 3);
if (ret == PX4_OK) {
/* fetch the raw value */
cvt->b[0] = buf[2];
cvt->b[1] = buf[1];
cvt->b[2] = buf[0];
cvt->b[3] = 0;
}
return ret;
}
int
MS5611_I2C::ioctl(unsigned operation, unsigned &arg)
{
int ret;
switch (operation) {
case IOCTL_RESET:
ret = _reset();
break;
case IOCTL_MEASURE:
ret = _measure(arg);
break;
default:
ret = EINVAL;
}
return ret;
}
int
MS5611_I2C::probe()
{
_retries = 10;
if ((PX4_OK == _probe_address(MS5611_ADDRESS_1)) ||
(PX4_OK == _probe_address(MS5611_ADDRESS_2))) {
/*
* Disable retries; we may enable them selectively in some cases,
* but the device gets confused if we retry some of the commands.
*/
_retries = 0;
return PX4_OK;
}
return -EIO;
}
int
MS5611_I2C::_probe_address(uint8_t address)
{
/* select the address we are going to try */
set_device_address(address);
/* send reset command */
if (PX4_OK != _reset()) {
return -EIO;
}
/* read PROM */
if (PX4_OK != _read_prom()) {
return -EIO;
}
return PX4_OK;
}
int
MS5611_I2C::_reset()
{
unsigned old_retrycount = _retries;
uint8_t cmd = ADDR_RESET_CMD;
int result;
/* bump the retry count */
_retries = 10;
result = transfer(&cmd, 1, nullptr, 0);
_retries = old_retrycount;
return result;
}
int
MS5611_I2C::_measure(unsigned addr)
{
/*
* Disable retries on this command; we can't know whether failure
* means the device did or did not see the command.
*/
_retries = 0;
uint8_t cmd = addr;
return transfer(&cmd, 1, nullptr, 0);
}
int
MS5611_I2C::_read_prom()
{
uint8_t prom_buf[2];
union {
uint8_t b[2];
uint16_t w;
} cvt;
/*
* Wait for PROM contents to be in the device (2.8 ms) in the case we are
* called immediately after reset.
*/
px4_usleep(3000);
uint8_t last_val = 0;
bool bits_stuck = true;
/* read and convert PROM words */
for (int i = 0; i < 8; i++) {
uint8_t cmd = ADDR_PROM_SETUP + (i * 2);
if (PX4_OK != transfer(&cmd, 1, &prom_buf[0], 2)) {
break;
}
/* check if all bytes are zero */
if (i == 0) {
/* initialize to first byte read */
last_val = prom_buf[0];
}
if (prom_buf[0] != last_val || prom_buf[1] != last_val) {
bits_stuck = false;
}
/* assemble 16 bit value and convert from big endian (sensor) to little endian (MCU) */
cvt.b[0] = prom_buf[1];
cvt.b[1] = prom_buf[0];
_prom.c[i] = cvt.w;
}
/* calculate CRC and return success/failure accordingly */
return (ms5611::crc4(&_prom.c[0]) && !bits_stuck) ? PX4_OK : -EIO;
}

Figure 18: Source code for MS5611 (PX4 source code)


Code analysis (optional)
There are a few things regarding this device driver example that is worth looking in more
detail, since they are common across the PX4 software.
This section requires knowledge of object-oriented programming and C++. Reading this
section is optional to the student.

1. This driver extends class device::I2C, this way, it is guaranteed it will expose the same I2C
common interface to all applications.
2. The code overrides methods read() and ioctl(), the 2 methods exposed to applications. This
is done so the driver implements the specific functionality for the MS5611 while
guaranteeing that these implementation details are hidden form the applications
3. The driver defines the addresses for writing and reading from the device. Since these are
hardcoded, any developer adding a device I2C device driver must be aware of these
predefined addresses, in order to avoid conflicts in the bus.
4. Most of the code is just formatting data to be sent to the device, as well as data sent back to
the application.
The actual reading and writing into the physical bus is done by method transfer(), which is
not implemented by this device driver but by the underlying I2C driver, which in turn relies
on a lower driver that actually communicates with the physical bus.
This shows how even device drivers are also implemented in layers and rely on lower level
functionality provided by other drivers.
Supplemental sensors
Sonars
Sonars are used in multi-propeller copters and drones in general as a
distance sensor. Collision Avoidance is one of the main applications for
this kind of sensor.
Sonars measure distance by echolocation: sonar emits a short pulse
and measures the time it takes for the pulse to return (time of flight).
Sonars are cheap compared to other types of distance sensors but are
not as precise; they cannot be used for high accuracy measurements and
safety purposes.
Since the time of flight is dependent on the speed of sound, which in
turn is dependent on air density and temperature, measurement accuracy will
be affected under different weather conditions.
Sonars are small and lightweight so it is common to install multiple
units pointing in different directions to provide wide coverage for obstacles.
Some sonars allow for connection in "daisy chain" so the master sonar only
has to trigger the first sonar measurement; after that each sonar triggers the
next in the chain once it is done with the distance measurement.
Sonar's maximum range is dependent on the size of the obstacle; the
larger the obstacle the further it can be detected. A good sonar datasheet will
provide graphs with bean shape and distance detection for obstacles of
different sizes and at different positions.
One example of such a device is the I2CXL-MaxSonar - EZ series of
devices [39]. This series of sonars is supported by PX4.
Lidars
Lidars are also distance sensors. Lidars use laser or focused light
pulses to measure distance and direction of an obstacle by measuring the time
of flight of a light pulse.
Prices for lidars can vary widely, depending on the application.
Lidars used to construct precise point maps of an environment can cost tens
of thousands of dollars. Even lidars used only as range finders can be quite
expensive, in the hundreds of dollars range.
Lidar's maximum range is affected by the obstacle's material; the
more reflective the surface the higher the range. The maximum range is also
affected by the width of the field of view; a wider field of view reduces the
maximum range.
Depending on the obstacle reflective properties and the field of view,
the range of a lidar can go from over 150 meters to only 6 meters.
Some lidars are connected to the flight controller using one of the
serial ports; therefore, the aircraft can be equipped with only one device;
others use I2C.
As a rule of thumb the lidar will be installed facing forward along the
main axis of the aircraft (assuming this is the usual direction of flight).
Lidar datasheets will normally provide a chart showing the amplitude
of the reflected laser signal versus the obstacle distance for different
materials with different reflective properties; the lowest signal level in the
chart will generally match the maximum distance for obstacle detection.
LeddarOne is an example of a relatively cheap, lightweight lidar for
drones [40]. It is currently supported by PX4.
Optical flow cameras
Optical flow cameras are specialized cameras mounted at the bottom
of a copter, facing down in a vertical direction. The cameras can be also
equipped with a rangefinder as well as a gyroscope.
The range finder is used to determine distance from the ground; the
gyroscope is used to determine the drone's rotation angle (rotation affects the
displacement calculation).
These cameras are used as a mechanism to keep the aircraft hovering
in place but can also be used for navigation. It is useful when flying a drone
in regions where GPS signal is inaccurate or absent (e.g. indoors flight).
The camera compares frames from the ground to measure the aircraft
displacement and provide that information to the controllers for correction
and control.
Optical flow cameras typically capture images at a high rate - around
400 Hz - and produce optical flow data to be used by the flight controller at
about 100 Hz, depending on the physical connection.
The main caveat when using optical flow cameras is that very
homogeneous ground patterns will reduce the camera's accuracy (e.g. flying
over grass).
Infra-red
Infra-red sensors are specialized cameras mounted at the bottom of
the copter, facing down in a vertical direction.
These sensors are used in conjunction with an infra-red light emitter,
normally positioned in areas where the copter must perform precise landing.
The copter flies to the general area where the emitter is and once it detects
the infra-red bean it can use the small displacements of the bean relative to
the camera to feed the controller and keep the copter aligned to the landing
point.
The main caveat with this type of sensor is the real estate they take
from the copter and the need for additional infra-structure at the landing site.
Another issue is infra-red emitted from the ground that can mask the bean
coming from the infra-red emitter.

Summary
For PID controllers to work, they must constantly compare the
current value of the variable of interest and setpoint for the variable.
Sensors are used to measure the current values for the variable of
interest.
Device drivers are software specifically designed to interact with
different sensors. device drivers abstract the details of the communication
protocol via a common software interface.
Core sensors are those necessary for controlled flight.
Supplemental sensors are those that provide additional functionality to the
UAV and may or may not be related to flight control.
Sensors interface with the flight controller via different physical
interfaces, typically I2C, SPI, CAN, USB and UART.
Actual software implementation of PID controllers can use
strategies that make calculations more efficient and less CPU intensive. For
example, by using direct measurements from sensors corresponding to the
derivative and integral values for the variable of interest, and manipulating
the setpoint for a convenient model.

Problems
1. Research for other examples of sensors that use I2C, SPI and CAN
interfaces and could be useful as either core or supplemental
sensors.
2. Regarding the device driver for the MS5611:
a. What do the following functions do?
i. read()
ii. ioctl()
b. What is the function transfer() used for?
3. Using the datasheet from the MB1030 LV-MaxSonar-EZ3, explain
how to use the bean pattern charts.
4. In the reference implementation of a PID controller, 2 of the inputs
are the variable of interest and its derivative. If the variable of
interest is horizontal speed, what would be its derivative? How
can it be measured?
Chapter 4 - Copter tuning and
calibration
Objectives
This chapter covers:
● Why sensors and ESCs must be calibrated
● How each sensor is calibrated
● The calibration procedure for the Pixhawk 4
Before a multi-propeller copter - and any drone for that matter - can
safely fly its core sensors must be calibrated. Flight controller software will
implement fail safes that prevent the aircraft from taking-off if it detects
uncalibrated sensors.
Sensor calibration is performed using specialized software classified
as Ground Control Systems (GCS). For PX4 running in the Pixhawk the
official ground control system is QGroundControl[18].
QGroundControl runs on a PC connected to the aircraft via a direct
connection using a USB cable, via WiFi or via a radio link with the
transmitter connected to a USB port in the PC.
When connected using the USB cable the flight controller
automatically prevents the drone from flying; this connection is normally
used for calibration or software debugging.
Finally, when connected using the RC radio link, QGroundControl
can be used for both calibration and flight.

Accelerometer
Accelerometer calibration is performed by connecting the aircraft to
the PC and positioning the aircraft in different orientations; since the
application knows where the drone is pointing to and that only gravity's
acceleration is applied it can determine measurement errors and flight
controller position relative to the drone and use these values to compensate
for measurement errors.
Magnetometer (compass)
Magnetometer calibration is the most difficult and unreliable.
Magnetic fields can be affected by so many factors - electric currents,
aircraft frame, environment, location, etc. - that it will be very difficult to
make precise and accurate compass heading measurements.
Magnetometer calibration is designed to remove hard-iron and soft-
iron magnetic offsets generated by components in the aircraft electronics
itself. Hard-iron interference is generated from permanently magnetized
components in the device while soft-iron offset is generated by temporarily
magnetized components (e.g. batteries, frame).
Calibration is accomplished by rotating the copter around all 3 axes
and assuming the hard and soft iron offsets are constant and move with the
aircraft, while the geomagnetic field does not. Therefore, by measuring the
field variation in every axis over time and applying a low-pass filter to the
signal, the DC component (or zero-frequency component) corresponds to the
hard and soft iron offsets and can therefore be subtracted from the
measurements; moving the aircraft quickly results in higher frequencies and
more accurate filtering of the DC component.
Calibration does not remove effects of the surrounding environment
to the geomagnetic field; buildings, minerals on the ground, electric wires,
etc. will still introduce errors to the compass measurements.
Because the calibration requires rotating the aircraft around its axis
in multiple orientations it is very difficult to execute with the drone
connected to the PC using the USB cable; it is much easier to perform using
the radio link.

Gyroscope
Gyroscope calibration is simple. Since this sensor is used to measure
rotational speed the calibration simply requires the aircraft to be placed on a
level surface without moving. The software can then calibrate the gyroscope
to reduce measurement errors.

Electronic Speed Controller (ESC)


A brushless DC motor will rotate at the required speed based on the
voltage applied to the terminals.
The voltage is controlled by an ESC connected to the motor input.
The ESC, in turn, knows how much voltage to apply to the motor based on a
periodic pulse produced by the flight controller. This pulse has a fixed
frequency but the pulse's width is changed depending on how much power
must be injected in the motor.

(Source: http s://en.wikip edia.org/wiki/File:Duty _Cy cle_Examp les.p ng


Credit: Thewrightstuff, License: CC BY-SA 4.0 , via Wikimedia Commons )

The principle behind PWM is relatively simple: the longer the


pulse, the longer the full voltage is applied to the motor. Therefore, the
average voltage - and consequently the motor average RPM - can be
controlled by changing the pulse width.
The maximum pulse width depends on the frequency of the pulses.
The time between 2 pulses is called period and defined as:

where:
T = period in seconds
f = pulse frequency in Hz
One aspect to be considered is that the pulse is not really a perfect
rectangle; in real life it takes a few microseconds for the signal to go from 0
to the maximum voltage. This is called slew rate.
For Pixhawk with PX4 it is typical to use a frequency of 400 Hz,
corresponding to a period of 2,500 µs so normally the maximum pulse is set
to 2,000 µs for 100% duty cycle and leaving 250 µs for the slew rate.
For the minimum value, the industry standard is 1000 µs.
As a rule, ESCs must be calibrated. Calibration is the process of
programming the ESCs with the maximum and minimum pulse width that will
be provided by the flight controller, as well as other parameters associated
with the ESC functionality. Calibration guarantees all ESCs will respond the
same way to a certain pulse width.
For the Pixhawk running PX4, calibration is performed by
QGroundControl. The software will set the maximum and minimum values
for the PWM pulse, safety features, etc. For a detailed description on how to
calibrate ESCs see [19].
About Oneshot protocol
It is worth mentioning that some ESCs support the Oneshot
protocol, which is also supported by Pixhawk 4 running on PX4. One of the
drawbacks of standard PWM is the 400 Hz frequency; it means that there’s
always a 1 - 2 ms delay between the flight controller and ESC before the
motor receives the new values for the voltage. For most applications this is
quite tolerable, but some applications - for example, racing - may require
faster reaction times.
Oneshot125 uses a higher frequency and shorter pulses to reduce the
delay. Oneshot125 uses pulses from 125 µs to 250 µs (maximum of 4 kHz).
When using Oneshot125, PX4 automatically converts the values set to
PWM_MAX to the proper pulse width.

PID controllers
As we've seen in the earlier chapters of this text, the PID controllers
are used for automatic management of the power supplied to the motors,
based on the setpoints for certain variables of interest.
PX4 implements several PID controllers that can be classified into
rate controllers and attitude controllers. These controllers work together in
order to provide the final throttle to each motor in the multi-propeller copter
so it can achieve the desired attitude.
The flight controller software implements multiple PID controllers
that monitor pitch, yaw, roll - both current values and rate of change -, both
vertical and horizontal speed and acceleration, trajectory, distance to
waypoint, altitude, etc.. All these PIDs contribute to the thrust of each
individual motor to achieve the behavior requested by the pilot.
Also the setpoint for several of these controllers is not fixed, but is
also the output of another PID controller. For example, the desired horizontal
speed is the output of a proportional controller that uses the distance between
the current position and the target position.
PX4 sets default values for the gains of these controllers; in general,
the derivative and integral controllers can be left alone, and only the
proportional controllers need to be adjusted by the designer.
As it can be seen, the implementation of PID controllers and their use
can be quite sophisticated and complex. Further study of the PX4 software is
recommended for a deeper understanding on how the software controls the
UAV flight.

Summary
Before safely flying the UAV, all sensors must be calibrated. In
fact, PX4, as a safety precaution, will not allow take-off until all calibration
is finished.
Each sensor must be calibrated to compensate for potential errors
inserted by the environment.
ESCs must also be calibrated so the flight controller can learn how
to regulate the PWM signals used to control the motors.
Finally, PID controllers must have their gains properly set.

Problems
1. Assuming a quadcopter in a “X” configuration, where the red
arrow indicates the front of the aircraft:
The pilot commands the UAV to fly at angle θ from North (Northeast
direction), at speed setpoint vd, while maintaining altitude and heading 00
(North).
Both horizontal speed and altitude are regulated by a proportional
controller, with gains Ks and Kh, respectively.

a. Show that, in order to generate controlled acceleration at the


desired direction, the horizontal thrust of each motor must be:

(Hint: the direction for the acceleration can be decomposed in 2


vectors, one pointing North and one pointing East; the proportional
controller can then be applied to the horizontal acceleration)

where:
Fxi = horizontal forces from each motor
b. What will be the total thrust applied to each motor in order to also
maintain the desired altitude hd?

The vertical thrust for each motor can be expressed as:

(Hint: it is not the sum of Fx and Fy )


Chapter 5 - On-board computing
Objectives
This chapter covers:
● Why add an on-board computer to the UAV
● Criteria to select the on-board computer
● Physical interfaces between the computer and the flight controller
● Communication protocol between the computer and the flight controller

Extending the UAV functionality


On-board computing is a powerful resource exposed by flight controllers to drone builders.
On-board computers allow drone builders to add functionality to a drone, otherwise not possible
due to the hardware limitations in flight controllers (CPU, memory, clock, etc.).
On-board computers also allow adding functionality that are not related to actual flight or may
require extra computing power and, therefore, are not suitable for running in the flight controller.
Some examples of applications that can be executed in the on-board computer are:
● Real-time video capture and transmission
● Machine-learning applications
● Cellular connectivity
● Intelligent collision avoidance
● Interface with instruments and sensors (e.g. RF detectors, spectrum analyzers, air quality sensors,
etc.)
Applications running in the on-board computer can be standalone apps, client-server apps or
apps that interact with the flight controller. Such apps communicate with the flight controller via some
physical interface - usually UART - and a communication protocol.
The next sections will focus on the most popular protocol for communication between the on-
board computer and the flight controller: MAVLINK.

Computer selection
When selecting the on-board computer that will be integrated with the flight controller several
aspects must be taken into account.

1. Weight
2. Size
3. Voltage and current
4. Computing power
5. Memory and storage
6. Peripherals

Let’s look at each one of these.

Weight
This one is quite obvious: heavier on-board computers will reduce the maximum payload that
can be carried by the aircraft. So favor systems that are a few grams and can operate for long periods of
time without refrigeration (e.g. electric fans).
Size
Real estate in the multi-copter is limited. An industrial multicopter that will carry several
pounds of payload, there is probably enough space for large motherboards equipped with powerful
CPUs.
If however this is a small drone there are several credit card sized computers available in the
market that are suitable for this type of application.
Voltage and current
Most CPUs are powered by a DC charger that provides 3.3, 5 or 12 volts, depending on the
power requirements of the computer. Be careful here: the batteries used in drones provide voltages as
integer multiples of 3.7 volts. In order to properly power the on-board computer a voltage regulator is
required.
When selecting a regulator, pay close attention to the input and output currents to make sure
they match the needs of the on-board computer and electronics used in the UAV.
Computing power
A relatively easy way to assess the computing power of an on-board computer is the clock: in
general, the higher the clock the faster the computer.
Other things to look at are: number of cores, number of threads per core and bus speeds.
Operating systems, programming languages and types of applications running in the on-board
computer are the main drivers for more or less computer power.
Applications written in C, running in a Real-Time Operating System (RTOS) like FreeRTOS or
QNX require much less computing power than a machine learning application written in Python and
running in a Linux-based OS like Ubuntu.
Applications that use AI or require processing large amounts of graphic content (e.g. video from
a camera) may require Graphics Processing Units (GPU) on top of the CPU.
Some research on board benchmarks using applications with similar functionality to the ones
running in the on-board computer will help.
As a rule of thumb, overestimate the specification: more computing power than needed doesn’t
hurt; less may cause catastrophic failure to the aircraft.
Memory and storage
Long gone are the days where memory and storage were prohibitively expensive and had to be
used with much care. Today one can buy 1 terabyte of storage for 150 bucks.
So when it comes to storage and memory there’s no reason to save; just go for the maximum
the on-board computer can use.
Peripherals
Here again the peripherals will be dependent on the application. In general a good general
purpose I/O (GPIO) interface with support for SPI, I2C and UART pins is a must; a few USB ports; an
Ethernet port; WiFi.
Other interfaces needed are video input and output, preferably HDMI, allowing interaction
with the computer for software installation and configuration.
The serial interface in the GPIO is the main interface with the flight controller; SPI and I2C
external interfaces are useful for additional sensors not connected to or supported by the flight
controller.
USB and Ethernet ports are needed for connecting WiFi and/or cellular modems.
Below is a list with characteristics of credit card sized on-board computers with high-end
specifications:
Name CPU/GPU Size Peripherals Volta Operatin
(Compa memory/ (mm)/ ge g
ny) storage weight /curr system
(g) ent
RPi 4 CPU: BCM2711, Quad core Cortex-A72 (ARM Size: 2 x USB 2.0 type-A 5V Raspberry Pi
(Raspberry v8) 64-bit SoC @ 1.5GHz 85.6mm × 2 x USB 3.0 type-A 3A OS
PI RAM: 8 GB 56.5mm 1 x Gigabit Ethernet
Foundation Disk: SD card (128 GB) Weight: 45 2 x mini HDMI out
) GPU: VideoCore VI g 40-pin GPIO (UART,
SPI, I2C)
WiFi
Bluetooth LE

BeagleBon CPU: AM5729 w/ 2 x Cortex-A15 @ 1,5 GHz Size: 1 x USB 3.0 type-C 5V Linux
eA RAM: 1 GB 89mm x 1 x USB 2.0 type-A 3A
(BeagleBoa Disk: eMMC 16 GB 54mm 2 x 46-pin headers with
rd GPU: 2 x SGX544 Weight: 48 PRU support
Foundation g
)

ROCKPro6 CPU: RK3399 w/ 1 x dual-core Cortex-A72 @ Size: 1x USB 3.0 type C Host 12 V Linux
4 2 GHz + 1 x quad-core Cortex-A53 @ 1.5 GHz 133mm x with DP 1.2 5A Android
(PINE64) RAM: 2 and 4 GB 80mm 1x USB 3.0 type A Host Unix
Disk: SD card/eMMC 256 GB Weight 2 x USB 2.0 Host
GPU: Mali-T860MP4 @ 650 MHz (w/ Gigabit Ethernet
RAM: heatsink): PI-2 GPIO Bus
136 g MiPi DSI
eDP
touch Panel stereo MiPi
CSI
PCIe
WiFi/BT
HDMI out

Coral CPU: NXP iMX 8M w/ 1 x Cortex-A53 @ 1,5 Size: 1 x USB Type-C power 5V Mendel Linux
(Google) GHz + 1 x Cortex-M4 microcontroller @ 120 85mm x port (5 V DC) 3A
MHz 56mm 1 x USB 3.0 Type-C
GPU: Vivante GC7000Lite Weight: OTG port
H/W codecs 138 g (w/ x USB 3.0 Type-A host
TPU: Edge TPU coprocessor (TensorFlow) fan) port
RAM: 4 GB 1 x USB 2.0 Micro-B
Disk: serial console port
eMMC 8GB HDMI out
SD card: - 40-pin GPIO
Gigabit Ethernet
WiFi/BT

ODYSSEY CPU: Intel® Celeron® J4105 @ 1.5 GHz Size: 1 × 40-Pin (Raspberry 12 V Windows 10
X86J41058 GPU: Intel® UHD Graphics 600 @ 750 MHz 110mm x Pi) 5A
00 RAM: 8 GB 110mm 1 × 28-Pin
(Seed) Disk: eMMC 64 GB Weight: 1 × 4-Pin UART
600 g (w/ 3 × 4-Pin SATA Power
heatsink) Connector
1 × 4-Pin Power and
Switch
2 x USB 2.0 Type-A
1 x USB 3.1 Type-A
1 x USB 3.1 Type-C
HDMI
2 x Gigabit Ethernet
4 x PCIe
WiFi

Jetson CPU: Quad-core ARM A57 @ 1.43 GHz Size: 69 4 x USB 3.0 Type-A 5V NVIDIA L4T
Nano GPU: 128-core Maxwell mm x 45 1 x USB 2.0 Micro-B 6A (derived from
(NVIDIA) RAM: 4 GB mm Gigabit Ethernet Ubuntu
Disk: SD card (> 16 GB) Weight: HDMI 18.04)
240 g DisplayPort
40-pin GPIO

Hikey 970 CPU: HiSilicon Kirin 970 w/ Quad-core Cortex- Size: 1 x 40-pin low-speed 12 V Android
(96Boards) A73 2.36GHz + Quad-core Cortex-A53 105.26mm header 2A Linux
@1.8GHz x 100mm 1 x 60-pin high speed
GPU: Mali-G72 MP12 Weight: header
RAM: 6 GB 150 g (UART, I2C, USB, etc.
Disk: SD card 64 GB
through the extension
headers)
WiFi
Bluetooth
GPS

On-board computer and flight controller interface - MAVLINK


MAVLINK is a de facto standard protocol for flight controllers using PX4 or other software
derived from it (e.g. ArduPilot).
MAVLINK 2.0 is the current version of the protocol and the one we'll describe in this section.
The full description of the messages can be found here [21].
The protocol uses packets with variable sizes, composed of a header and a payload. The header
conveys information like the message ID and the packet length; the payload has the command parameters
or data from the flight controller. The content and length of the payload depends on the message being
exchanged.

Field Size Description


STX 1 byte 0xFD
Marks the beginning of a new packet
LEN 1 byte Payload length
INC 1 byte Incompatibility flags
FLAGS Used for flags that the system must understand otherwise, it will not be
able to process packets properly.
Currently only flag is 0x01: indicates if the packet is signed or not
CMP 1 byte Compatibility flags
FLAGS Used for flags that can be safely ignored by the system
SEQ 1 byte Sequence number (0-255)
SYS ID 1 byte System ID
PX4 defines it as 0x01 by default. Can be changed if using multiple
flight controllers
COMP ID 1 byte Component ID
PX4 uses 0x01 (autopilot)
MSG ID 3 bytes Message ID
(LSB
order)
Payload 0 to 255 Message content (command or data)
bytes
Checksum 2 bytes CRC value from the packet content
Signature 13 bytes Message signature using a shared key
(optional)
More details on the packet content and format can be found in [20]
MAVLINK is a quite complex protocol since it’s designed to support a large variety of vehicles -
rovers, copters, boats, fixed wing aircrafts, VTOL, etc. - and accessories/sensors - cameras, gimbals,
lidars, optical flow cameras, etc; therefore, sometimes it is possible to execute the same action using
different combinations of commands.
Another aspect that must be kept in mind is that implementations may not support all commands
and messages.
Messages and commands
MAVLINK defines several messages and commands. In the documentation, commands start with
MAV_CMD.
As a rule, only messages are exchanged between the on-board computer and the flight controller;
therefore, commands must be encapsulated in a message.
Messages
Messages are used by the on-board computer for both sending and receiving data; in general
messages are used for providing periodic telemetry, heartbeat, ping, set/read parameters, encapsulate
commands, etc.
Examples of messages are:
COMMAND_INT
COMMAND_LONG
SET_MODE (now deprecated and replaced with command MAV_CMD_DO_SET_MODE, but still
supported in PX4)
HEARTBEAT
PING
NAV and DO commands
MAVLINK classifies commands in 3 categories:
● Navigation commands: commands starting with MAV_CMD_NAV and used exclusively for
flying the aircraft, in general within missions. Some examples are:
MAV_CMD_NAV_TAKEOFF
MAV_CMD_NAV_LAND
MAV_CMD_NAV_RETURN_TO_LAUNCH
MAV_CMD_NAV_WAYPOINT
● Immediate action commands: commands starting with MAV_CMD_DO; these commands are
normally used to override a navigation command, a mission item or execute some necessary
action. Examples are:
MAV_CMD_DO_FOLLOW
MAV_CMD_DO_REPOSITION
MAV_CMD_DO_JUMP
MAV_CMD_DO_GIMBAL_MANAGER_ATTITUDE
● General commands: other commands starting with MAV_CMD but not used for navigation or
immediate action. For example:
MAV_CMD_REQUEST_AUTOPILOT_CAPABILITIES
MAV_CMD_REQUEST_PROTOCOL_VERSION
MAV_CMD_REQUEST_FLIGHT_INFORMATION
MAV_CMD_SET_MESSAGE_INTERVAL
MAVLINK defines 2 messages that function as wrappers around commands:
COMMAND_INT (message ID = 75)
This message is used to encapsulate commands with up to 7 parameters when the payload is a
command with parameters as scaled integers.
COMMAND_LONG (message ID = 76)
This message is used to encapsulate commands with up to seven parameters represented by
floating precision numbers (4 bytes each)
Connecting to the flight controller

Figure 11 shows the terminals in the Pixhawk. Terminals TELEM 1 and TELEM 2 are UARTs
that allow an on-board computer to transmit commands and receive messages from the flight controller.
In general the on-board computer must be connected only to TELEM 1 to transmit commands to
and receive messages from the flight controller.
TELEM 1 uses a serial UART interface that must be configured with the same attributes as the
on-board computer serial interface; the configuration parameter depends on the software running in the
flight controller as well as the flight controller hardware.
For PX4, use QGroundControl to change the following parameters:

Parameter Value Description


MAV_0_CONFI 101 Configure MAVLINK to run in the TELEM 1 port
G (default
)
SER_TEL1_BA 115200 115200 bits per second
UD
The configuration is always 8-N-1 (8 bits, no parity, 1 stop bit); make
sure the on-board computer serial port is setup the same way
MAV_0_MODE 0: Enable different sets of unsolicited messages at different rates
Normal
(default
)
2:
onboard

Set it to
2
Table 1: Configuration parameters for serial port TELEM 1
Message types
There are 2 types of messages that can be received over TELEM 1: responses to commands and
unsolicited messages.
Response to commands are normally messages containing data requested by the on-board
computer (e.g. HOME_POSITION message as response to a MAV_CMD_GET_HOME_POSITION
command).
Unsolicited messages are messages sent by the flight controller, either periodically or as a
response to an event (e.g. periodic message GPS_RAW_INT). Which messages and how often these
messages are sent depends on the software running in the Pixhawk.
For PX4 running MAVLINK in on-board mode the unsolicited messages are listed in Table 2.
Not all messages in Table 2 are available - or useful - to a multi-propeller copter; the ones
important for controlling the multi-propeller copter from an on-board computer are marked in bold and
italic.

Rate
Message
(messages/second)
TIMESYNC 10.0f
CAMERA_TRIGGER unlimited_rate
HIGHRES_IMU 50.0f
LOCAL_POSITION_NED 30.0f
ATTITUDE 100.0f
ALTITUDE 10.0f
DISTANCE_SENSOR 10.0f
MOUNT_ORIENTATION 10.0f
OBSTACLE_DISTANCE 10.0f
ODOMETRY 30.0f
ACTUATOR_CONTROL_TARGET0 10.0f
ADSB_VEHICLE unlimited_rate
ATTITUDE_QUATERNION 50.0f
ATTITUDE_TARGET 10.0f
BATTERY_STATUS 0.5f
CAMERA_CAPTURE 2.0f
CAMERA_IMAGE_CAPTURED unlimited_rate
COLLISION unlimited_rate
DEBUG 10.0f
DEBUG_FLOAT_ARRAY 10.0f
DEBUG_VECT 10.0f
ESTIMATOR_STATUS 1.0f
EXTENDED_SYS_STATE 5.0f
GLOBAL_POSITION_INT 50.0f
GPS2_RAW unlimited_rate
GPS_RAW_INT unlimited_rate
HOME_POSITION 0.5f
NAMED_VALUE_FLOAT 10.0f
NAV_CONTROLLER_OUTPUT 10.0f
OPTICAL_FLOW_RAD 10.0f
ORBIT_EXECUTION_STATUS 5.0f
PING 1.0f
POSITION_TARGET_GLOBAL_INT 10.0f
POSITION_TARGET_LOCAL_NED 10.0f
RAW_RPM 5.0f
RC_CHANNELS 20.0f
SERVO_OUTPUT_RAW_0 10.0f
SYS_STATUS 5.0f
SYSTEM_TIME 1.0f
TRAJECTORY_REPRESENTATION_WAYPOINTS 5.0f
UTM_GLOBAL_POSITION 1.0f
VFR_HUD 10.0f
VIBRATION 0.5f
WIND_COV 10.0f
HEARTBEAT 1.0f
Table 2: List of unsolicited MAVLINK messages in on-board mode
Flying the multi-propeller copter
There are 2 basic mechanisms for flying the multi-propeller copter using MAVLINK: MIssion
Protocol and the Command Protocol.
The Mission Protocol allows the operator to push a complete set of commands to the flight
controller and let it take care of the whole mission. This is a case where the on-board computer is used
for other activities that are not related to the flight itself (e.g. capturing and transmitting real-time video).
The Command Protocol all allows the on-board computer to send single commands to the flight
controller as required by the current situation. In this work, we’ll focus on the Command Protocol, since
that’s where the power of an on-board computer is more relevant.
Frames of reference and modes of operation

MAVLINK defines 12 different frames of reference (there’s 1 additional frame -


MAV_FRAME_MISSION - that is not a real frame, it’s just used by the protocol to indicate a command
is part of a mission); each frame is global or local and uses a different coordinate system. Several
messages provided by the flight controller - especially the ones conveying position and attitude
information - will include the frame of reference for the data provided.
Frame information is also included as a parameter of COMMAND_INT messages; however,
frame of reference is not used in COMMAND_LONG messages, indicating that commands wrapped in
these messages either are independent of the frame or use a global frame by default.
Modes of operation are defined by a bitmask with different combinations of 8 flags:

Val
Field Name
ue
128 MAV_MODE_FLAG_SAFETY_ARMED
64 MAV_MODE_FLAG_MANUAL_INPUT_ENABLED
32 MAV_MODE_FLAG_HIL_ENABLED
16 MAV_MODE_FLAG_STABILIZE_ENABLED
8 MAV_MODE_FLAG_GUIDED_ENABLED
4 MAV_MODE_FLAG_AUTO_ENABLED
2 MAV_MODE_FLAG_TEST_ENABLED

1 MAV_MODE_FLAG_CUSTOM_MODE_ENABLED

As a convenience, MAVLINK pre-defines 12 different modes of operation:

Val Field Name


ue
0 MAV_MODE_PREFLIGHT
80 MAV_MODE_STABILIZE_DISARMED
208 MAV_MODE_STABILIZE_ARMED
64 MAV_MODE_MANUAL_DISARMED
192 MAV_MODE_MANUAL_ARMED
88 MAV_MODE_GUIDED_DISARMED
216 MAV_MODE_GUIDED_ARMED
92 MAV_MODE_AUTO_DISARMED
220 MAV_MODE_AUTO_ARMED
66 MAV_MODE_TEST_DISARMED
194 MAV_MODE_TEST_ARMED

But the modes of operation are not restricted to these; on top of that, MAVLINK allows for
additional custom flags that are implementation-dependent (e.g.
PX4_CUSTOM_MAIN_MODE_AUTO) and not always well documented.
Core flight commands

Despite the complexity of the protocol, the fact is that, in order to fly a multi-propeller copter,
only a handful of commands is required.
Flying a multi-propeller copter can be summarized in 7 operations:

Flight Description
operations
Turn on the motors; propellers are spinning but not fast enough for the
1. Arm copter to start flying
motor
s

multi-propeller copter vertically ascends to a predefined altitude


2. Take-
off

Go to positions defined by its latitude and longitude.


3. Go to
wayp
oint

Change altitude. Altitude can be relative to the seal level (AMSL), to


4. Chang the ground or to the current altitude (altitude offset)
e
altitud
e

Hover in place
5. Hover

multi-propeller copter vertically descends to the ground until


6. Land touchdown

Stop motors
7. Disar
m
motor
s

These steps can be accomplished with different combinations of commands. This is how
QGroundControl does it:

Operation Message
Arm motor COMMAND_LONG (76)
Command: 400 (MAV_CMD_COMPONENT_ARM_DISARM)
Param1: 1 (arm)
Param2: 0 (does not bypass safety checks)
Take-off SET_MODE (11)
Base_mode: 157 (bitmask 10011101) = safety_armed, stabilize_enabled,
1. Set the guided_enabled, auto_enabled, custom_mode_enabled)
required Custom main mode: 4 = PX4_CUSTOM_MAIN_MODE_AUTO
flags Custom sub mode: 3 = PX4_CUSTOM_SUB_MODE_AUTO_LOITER (will
2. Send hover once take-off altitude is reached)
command COMMAND_LONG (78)
to take-off Command: 22 (MAV_CMD_NAV_TAKEOFF)
Param1: -1 (pitch, not applicable for copter)
Param7: AMSL
Go to waypoint COMMAND_LONG
Command: 192 (MAV_CMD_DO_REPOSITION)
Param1: -1 (default speed)
Param2: 1 (aircraft immediately transition to guided mode)
Param4: NaN (yaw = uses current yaw setting)
Param5: <destination latitude>
Param6: <destination longitude>
Param7: <destination AMSL>
Change altitude COMMAND_LONG
Command: 192 (MAV_CMD_DO_REPOSITION)
Param1: -1 (default speed)
Param2: 1 (aircraft immediately transition to guided mode)
Param4: NaN (yaw = uses current system yaw, for example yaw towards next
waypoint)
Param5:NaN
Param6: NaN
Param7: <destination AMSL>
Hover COMMAND_LONG
Command: 192 (MAV_CMD_DO_REPOSITION)
Param1: -1 (default speed)
Param2: 1 (aircraft immediately transition to guided mode)
Param4: NaN (yaw = uses current yaw setting)
Param5:NaN
Param6: NaN
Param7: NaN
Land SET_MODE (11)
Base_mode: 157 (bitmask 10011101) = safety_armed, stabilize_enabled,
guided_enabled, auto_enabled, custom_mode_enabled)
Custom main mode: 4 = PX4_CUSTOM_MAIN_MODE_AUTO
Custom sub mode: 6 = PX4_CUSTOM_SUB_MODE_AUTO_LAND
Disarm COMMAND_LONG (76)
Command: 400 (MAV_CMD_COMPONENT_ARM_DISARM)
Param1: 0 (disarm)
Param2: 0 (does not bypass safety checks)

So it is clear that, despite the fact that MAVLINK provides a large set of navigation commands
for all these operations, the multi-propeller copter can be fully operated using only 2 commands and 1
message - MAV_CMD_COMPONENT_ARM_DISARM, SET_MODE and
MAV_CMD_DO_REPOSITION - for all flight operations.
Parameters and settings
PX4 provides over 600 parameters that can be configured by the aircraft operator.
For the commands described in the previous section just a few parameters are relevant,
especially for the ones that explicitly used the default value or current settings:

Parameter Description Range Defa


ult
MPC_TKO_SPEED Takeoff climb rate 1.00 - 1.5
5.00 m/s m/s
MIS_TAKEOFF_ALT Takeoff altitude (relative to the ground; used by on- 0.00 - 10.0
board computer to calculate AMSL) 80.0 m m
MPC_LAND_SPEED Landing descent rate 0.2 - m/s 0.5
m/s
MPC_Z_VEL_MAX_ Maximum vertical ascent velocity (for changing altitude) 0.5 - 8.0 3.0
UP m/s m/s
MPC_Z_VEL_MAX_ Maximum vertical descent velocity 0.5 - 4.0 1.0
DN m/s m/s
MPC_XY_CRUISE Nominal horizontal velocity 3.0 - 5.0
20.0 m/s m/s
(1)
MPC_XY_VEL_MAX Maximum horizontal velocity 0.0 - 12.0
20.0 m/s m/s

(1) If this value is capped by MPC_XY_VEL_MAX

Available libraries
When developing software for the onboard computer that will take advantage of MAVLINK,
using pre-existing tested libraries implementing the protocol makes life much easier.
mavgenerate[27] is the de-facto standard tool for developers that need to build a MAVLINK
library for their application. mavgenerate provides a graphic user interface for the developer to use
when generating the source code.
mavgenerate currently supports C, CS-4, JavaScript, TypeScript, Python, Lua, WLua, ObjC,
Swift, Java and C++-11.
In order to use mavgenerate the developer must do the following (these are commands for
machines running some flavor of Linux)
1. Install Python 3
2. Install the future module: pip3 install future
3. If using Linux to run the tool, install TkInter: sudo apt-get install python3-tk
4. Create a folder and download the tool in it: git clone
https://github.com/mavlink/mavlink.git --recursive

Under <installation folder>/mavlink/message_definitions/v1.0 there is a set of XML files;


these files define the messages, parameters and commands supported by MAVLINK and are used by the
tool to generate the source code to be integrated in the application.
minimal.xml and common.xml have the list of messages common across all devices; the other
XML files define extensions that are proprietary to each platform.
Notice that none of these files include the PX4 custom modes so, if needed, then create a file
called px4.xml in the same folder as the other XML files, with the following content:

<?xml version="1.0"?>
<mavlink>
<include>common.xml</include>
<version>3</version>
<dialect>0</dialect>
<enums>
<enum name="PX4_CUSTOM_MAIN_MODE">
<entry value="1" name="PX4_CUSTOM_MAIN_MODE_MANUAL"/>
<entry value="2" name="PX4_CUSTOM_MAIN_MODE_ALTCTL"/>
<entry value="3" name="PX4_CUSTOM_MAIN_MODE_POSCTL"/>
<entry value="4" name="PX4_CUSTOM_MAIN_MODE_AUTO"/>
<entry value="5" name="PX4_CUSTOM_MAIN_MODE_ACRO"/>
<entry value="6" name="PX4_CUSTOM_MAIN_MODE_OFFBOARD"/>
<entry value="7" name="PX4_CUSTOM_MAIN_MODE_STABILIZED"/>
<entry value="8" name="PX4_CUSTOM_MAIN_MODE_RATTITUDE"/>
<entry value="9" name="PX4_CUSTOM_MAIN_MODE_SIMPLE"/>
</enum>
<enum name="PX4_CUSTOM_SUB_MODE_AUTO">
<entry value="1" name="PX4_CUSTOM_SUB_MODE_AUTO_READY"/>
<entry value="2" name="PX4_CUSTOM_SUB_MODE_AUTO_TAKEOFF"/>
<entry value="3" name="PX4_CUSTOM_SUB_MODE_AUTO_LOITER"/>
<entry value="4" name="PX4_CUSTOM_SUB_MODE_AUTO_MISSION"/>
<entry value="5" name="PX4_CUSTOM_SUB_MODE_AUTO_RTL"/>
<entry value="6" name="PX4_CUSTOM_SUB_MODE_AUTO_LAND"/>
<entry value="7"
name="PX4_CUSTOM_SUB_MODE_AUTO_RESERVED_DO_NOT_USE"/>
<entry value="8" name="PX4_CUSTOM_SUB_MODE_AUTO_FOLLOW_TARGET"/>
<entry value="9" name="PX4_CUSTOM_SUB_MODE_AUTO_PRECLAND"/>
</enum>
<enum name="PX4_CUSTOM_SUB_MODE_POSCTL">
<entry value="0" name="PX4_CUSTOM_SUB_MODE_POSCTL_POSCTL"/>
<entry value="1" name="PX4_CUSTOM_SUB_MODE_POSCTL_ORBIT"/>
</enum>
</enums>
<messages/>
</mavlink>

To generate the library source code, just do the following:


1. Go to <installation folder>/mavlink
2. Run mavgenerate.py. This UI will be presented:
3. Click “Generate”
4. Copy the generated files to the development environment, if needed

The generated code is thoroughly commented on so it is relatively easy to understand how to


use the exposed APIs to encode and decode MAVLINK messages.
One last comment: if generating Javascript and Python libraries, the tool generates a single file -
.js for Javascript and .py for Python - with the whole code in it.
Once the code is generated, the developer can integrate it with its own application if it needs to
communicate with the flight controller.

Summary
On-board computing is useful for adding functionality to the UAV beyond simply flying.
On-board computers can be used to:
● Run applications to control and interact with on-board equipment (e.g. cameras, scientific
instruments, etc.)
● Run applications to interact with the web
● Run AI software that will control the UAV autonomously (e.g. power line inspection UAV)
The appropriate size for the on-board computer will depend on the payload capacity,
application and size of the aircraft. It can go from small microcontrollers to powerful, full-size
computers running multiple CPUs and GPUs.

Problems
1. (Requires knowledge of computer programming) Using the generated source code for one
of the programming languages (examples here), write a small program for RPi 4 that
generates the MAVLINK messages used for flying the UAV
Chapter 6 - Designing a multi-
propeller copter
Objectives
This chapter covers:
● Propeller thrust and consumed electrical and mechanical power
● Propeller and motor key parameters
● Batteries, ESCs and power distribution
● Electronic components on board of the UAV
● UAV parts and mechanical structure
● Systematic calculation procedure for propellers, motors, power and
frame parts

Formulas and definitions


Payload and weight ratio
Like any transport vehicle, the “empty” vehicle weight - called
deadweight - will always be a few times higher than the useful payload. For
example, cargo ships weighing 165,000 tons can carry about 25,000 tons of
cargo - around 15% of the deadweight. A typical intermediate passenger’s
car will weigh around 3,000 lbs and carry up to 1,500 lbs, about 50% of the
deadweight.
Large cargo aircrafts - like the Antonov 124-100 or the Mi-26
helicopter - are more efficient, being able to carry about 80% of their
deadweight in cargo.
When calculating the parameters for the copter propellers and
motors, there are 5 elements to take into account:
● Frame (drone body, arms, legs or landing gear, mounting plates)
● On-board electronics (ight controller, RC receiver, on-board
computer, cellular modem)
● Payload
● Motors + propellers
● Batteries and power distribution
This section describes how to make initial estimates for the weight of
these parts and then refine the results to reach the desired UAV design.
As a rule of thumb, the copter must be able to hover in place, with the
maximum payload, using about 50% of the maximum available thrust; this
rule leaves enough power for normal operation (take-off, navigation, etc.).
Therefore, the maximum thrust using full throttle on the propellers is
set as:

(6.1)
where:
TT = maximum total thrust from all motor-propeller pairs in Newtons
WB = weight of one battery
WP = maximum weight of payload
WFM = estimated weight of frame + motors
n = number of batteries
As indicated above, at maximum thrust, the motor-propeller pairs
are consuming the maximum available electrical power, given by:
(6.2)
where:
PE = available electrical power per motor-propeller pair
IM AX = maximum safe current provided by batteries (limited by wiring and
battery connectors)
VE = voltage applied to the on-board electronics (typically 5 V)
IE = current consumed by the on-board electronics (depends on the UAV
configuration)
Thrust, power and motor specification
In this chapter only DC electric brushless motors, by far the most popular motors for copters, are
considered. These motors are compact, durable, precise, lightweight and affordable.
A brushless electric motor is characterized by its kV rating, the motor’s constant velocity. This
number conveys the RPM per volt applied to the motor.
Propellers are characterized by 3 parameters: diameter, number of blades and pitch. In this
analysis the propeller is assumed to have 2 blades.
The ideal static thrust generated by one motor-propeller pair is given by: [22]

(6.3)

(6.4)
where:
TM = thrust per motor-propeller pair in Newtons
D = diameter of the propeller in meters
p = propeller pitch in meters
RPM = revolutions per minute of the motor-propeller pair
ρ = air density (1.225 kg/m3)
N = number of motor-propeller pairs
The mechanical power transmitted by the motor to the propeller is given by [22]:

(6.5)

(6.6)
where:
PEM = electrical power consumed by each motor-propeller pair in watts
PM M = useful power provided by the motor to the propeller
N = number of motor-propeller pairs
The kV rating of the motor is given by:

(6.7)
where:
kV = motor’s constant velocity or kV rating
RPM = rotations per minute of the motor-propeller pair
V = voltage applied to the motor’s terminals
The thrust and power formulas work for a pitch-to-diameter ratio up to 1:2; after that the
propeller efficiency is reduced due to several aerodynamic factors and further increases in pitch only
provide marginal increase in thrust.

Battery
Copters typically use lithium-polymer (LiPo) batteries for power.
LiPo batteries are built using 3.7 V cells connected in series and.or parallel to provide the
total voltage output and capacity of the battery; cells with different sizes have different capacities.
There are a few characteristics that must be considered when selecting the batteries:
● Capacity (mAh): the maximum charge a battery can hold.
○ The higher the capacity, the longer the copter can fly
● Discharge rating “C”: maximum safe current divided by the capacity
○ Use this to make sure the maximum current required by the UAV is below this absolute
upper limit
● Voltage (V): the maximum total voltage that can be supplied by the battery.
○ The higher the voltage, the higher the maximum RPM delivered by the motor; also some
motors are designed to work with a range of voltages
● Weight (g): the battery weight
○ Batteries within the same classification can have different weights
● Connector type and wire gauge: the connector type and wire gauge constrain the actual maximum
current that can be output by the battery
○ For example, an XT60 connector type allows for 60 A maximum current but a typical 12
AWG terminal wire allows only for a maximum of 40 A (more than that and the wire will
overheat).
There’s no explicit equation correlating the battery parameters with its weight, we’ll have to
rely on tables mapping these values; in any case it can be considered the battery weight as a function -
albeit unknown - of the capacity.
Here is a chart for weight x capacity:

Figure 19: Battery capacity x weight

Electronic Speed Controller (ESC) current


As it was discussed in previous sections, the ESC is an essential part of the design when using
brushless DC motors. The flight controller provides a PWM signal to the ESC which, in turn, translates
it into a fraction of the total voltage available from the batteries and feeds that into the motor.
A multi-propeller copter will have 1 ESC per motor, and it must be able to handle the
maximum current consumed by the motor-propeller pair when spinning at maximum RPM.
The equation for the minimum current a ESC must support is simple:

(6.8)
where:
IESC = minimum ESC current
PEM = electrical power consumed by each motor-propeller pair in watts
V = batteries voltage

Flight duration
By definition, the flight duration depends on the number of batteries and the total current drained
by the UAV:

(6.9)
where:
FD = flight duration
C = capacity of each battery
ID = total current consumed by the drone
n = number of batteries
However, as it was mentioned before, there are constraints on the maximum current a LiPo
battery can effectively provide, from both the connector type and the wire gauge.
So, in reality, the total current consumed by the UAV must be:

where:
IM AX = maximum safe current per battery

Replacing this relation in (6.9) and rearranging the terms results:

(6.10)
In other words, the minimum flight duration does not depend on how many batteries are
installed. This is an important result, since it helps to eliminate configurations that do not meet the
minimum flight duration requirements right away.
For example, if a minimum flight duration of 30 minutes is required and the maximum current
that can be safely provided by the battery is 30 A (due to connector size and wire gauge), then only
batteries with capacity above 15000 mAh must be considered.

Calculation procedure
Before proceeding with the calculations, a word of advice: as it was studied in the first
chapters, the equations and formulas used here are models for the behavior of the components; as such,
they are approximations and many variables and factors are left out.
In general, the values calculated here will have a 25% error when compared with the numbers
provided by the manufacturer, and will be valid up to about 10000 revolutions per minute and a pitch-to-
diameter ratio of about 1:2; after that, other losses and inefficiencies become more relevant and affect
the available power and thrust.
The calculations also assume a 2-blade propeller; using a 3 or 4 blades propeller requires
adjustments to the equations.
The variables in our system of equations are:
V, C, IM AX and ID = voltage and current parameters
D, p = propeller’s diameter and pitch
kV = motor parameter
PM M . PEM , TM and RPM = power - both mechanical and electrical - , thrust and RPM per motor-
propeller pair
n, N = number of batteries and motor-propeller pairs
WP, WFM , WB= weights of the payload, frame and batteries, respectively

It’s clear that there are way more variables than equations, so it is not possible to resolve the
system of equations without postulating arbitrary values or constraints for some of the variables.
Besides, because the system is composed of nonlinear equations, it is difficult to resolve it
analytically. Therefore, a numeric approach is used.
The spreadsheet with these formulas and calculations is downloadable from [24]; the chart with
battery parameters used for the calculations can be found here [25].
Repeat the calculations using different numbers for the payload, frame weight and number of
propellers and batteries, until a suitable configuration shows up.
It’s not a problem to overestimate the numbers and end up with a UAV with more capacity than
required. An overdimensioned UAV is safe; in the best case, an underdimensioned aircraft will not fly;
in the worst it will fly haphazardly and be a danger to its surroundings. Do not underestimate the damage
a fiberglass blade, spinning at 7000 RPM, can make.
Step 1: Define the design constraints
In this step, enough variables must be set so that it is possible to calculate the remaining
parameters from these constraints.
There are no set rules for which variables must be set. For this procedure it is assumed that
the following variables are selected:
1. WP = the maximum payload to be carried by the UAV
2. WFM = estimated weight of the frame, including electronics and motors. A good rule of
thumb for an initial estimate is to make the frame’s weight 2 times the payload.
3. IE = estimate for the current consumed by the on-board electronic components
4. IM AX = maximum safe current; it will depend on the battery connectors and wires and
number of batteries. For batteries using an XT60 connector and 12 AWG wires, 30 A per
battery is safe; for XT90 with 10 AWG wires 50 A per battery is fine.
5. VE = voltage applied to the electronics. It is usually 5 V, depending on the electronics on
board.
6. n = number of batteries; 2 batteries is common. Some heavy lifting UAVs can carry up to 6
batteries.

Observe that equation (6.5) shows an exponential relationship between mechanical power and
thrust.
This relationship is one of the reasons why adding more batteries to the UAV does not
necessarily increase the flight duration significantly, especially if the batteries are a major contributor to
the overall aircraft weight.
Just as an example, let’s say one battery represents 50% of the total weight; adding a new
battery means increasing the required thrust by 50%; the corresponding increase in required power will
be 80%. So the capacity is doubled, but the power requirement is also almost doubled; the gain in flight
duration will be about 10%.
On the other hand, if the batteries represent only 10% of the total weight, adding a new battery
can increase flight duration by about 75%.
It is important to keep these in mind when selecting the battery type and number of batteries for
the UAV.
The next steps are repeated for each battery and different number of motor-propeller pairs.
● 4, 6 and 8 motor-propeller pairs are common configurations, but others are possible. In order to
expedite the calculations, using the spreadsheet is recommended.
● The following variables come from the batteries specifications: V, C and WB. Use then in the
calculations described in the next steps
Step 2: Calculate F D, TT and TM

Use Equations (6.1) for TT , (6.4) for TM . Use each battery weight for WB.
Use Equation (6.10) for FD. As stated before, if the flight duration is a constraint, its value can
be used to eliminate unsuitable configurations. Use each battery capacity for the value of C.
Step 3: Calculate P E, P EM and P MM

From (6.2), calculate PE. This is the maximum electrical power available for the motors,
running at full thrust. Use each battery voltage for the value of V.
From (6.6) calculate PEM . This is the maximum electrical power available per motor-
propeller pair.
From (6.5) calculate PM M as a fraction of PEM . As indicated in the expression, make PM M
about 85% of PE.

Step 4: Calculate the propeller’s pitch and diameter (p and D)


From (6.5), the expression for the propeller’s diameter is:

where:
PM M = available mechanical power from step 3
TM = thrust per motor from step 2

Make the pitch half of the diameter. As indicated before, beyond that the models do not stand
since other aerodynamic effects become more relevant.

Step 5: Calculate maximum RPM


Rearranging Equation (6.5) and isolating RPM results:
where:
RPM = maximum revolutions per minute for maximum thrust
D = diameter of the propeller from step 4
p = pitch of the propeller from step 4
TM = thrust per motor-propeller pair from step 2
⍴ = density of air = 1.225 kg/m 3
Step 6: Calculate motor’s kV
Use Equation (6.7) to calculate kV using the RPM from step 5. Use the battery voltage for the
value of V. If using more than one battery, assume they are mounted in parallel and are identical so the
voltage applied is the same as one battery.
Step 7: Calculate the minimum current for the ESC
Use Equation (6.8) to calculate the minimum specification for the ESCs. Use the battery voltage
for V and PEM from step 3.

The next sections will use the propeller dimensions to calculate the size of the frame - arms,
body and landing gear/legs - and kV to find a suitable motor.

Frame size
In this section it is assumed a symmetric geometry will be used for the calculations.
As mentioned in previous sections, using pairs of counter-rotating propellers, mounted
symmetrically opposite to each other, makes it easier to compensate for the angular momentum and better
control the copter’s yaw.
Therefore, an even number of motor-propeller pairs is typical when designing copters. If an
odd number of motor-propeller pairs is a hard requirement, one solution is to use 2 counter rotating
propellers on each arm of the copter; another, more complicated approach from a system control
perspective, is to have the motors turning at different RPMs.
The calculations from the previous section provided the following information:

1. Number and diameter of propellers


2. Number and size of batteries
3. Number of motor-propeller pairs

From these numbers the size of the copter’s body, as well as the length of each arm, can be
calculated.

Battery position and arrangement


Batteries must be layered underneath the copter’s body so they do not interfere with other
components or payload placed under the aircraft; also, as the heaviest component of the unloaded copter,
they are the main contributors for the position of the center of mass, which must be below the plane of
the propellers.
The number of batteries per layer and position must be such that the arrangement is as
symmetric as possible with reference to the UAV frame. If the center of mass is not centralized the lift
provided by each propeller will be unbalanced the control system may have difficulties stabilizing the
copter.
Figure 20: in a) the center of the drone (black X) coincides with the center of mass (red X); in b) the
center of mass is off-center and the lifts in each propeller will be unbalanced
Battery holder or plate
A battery mount plate or battery holder may be necessary for holding the batteries in place
during flight. If using one, it is recommended to install it under the drone’s body to keep the center of
gravity below the plane of propellers.
Batteries come in different sizes so, if using a battery plate, use straps or belts to hold the battery
in place.
Example: CS053 octocopter battery plate, Tarot FY680 Foldable Battery Mount Plate
Battery straps
Use at least 2 straps or belts per battery. Make sure they are long enough to wrap around the
battery and be securely fastened.
Example: Graphene Battery Strap, Apex RC Products HD Rubberized Battery Straps,
Crazepony Battery Velcro Straps
Figure 21: Example of a battery mount plate with battery straps

Arms length
The length of each arm will depend on the size and number propellers as well as the copter
shape. and structure.
Assuming the N propellers are distributed symmetrically and radially around the copter’s
center body, then the center of each propeller corresponds to the vertex of a regular polygon with N
sides.
The length of the side of a regular polygon is related to the distance between the vertex and the
center of the polygon by this formula:

where:
L = distance between center of motor-propellers pairs
R = length of each arm
N = number of sides of the polygon
Therefore:

The distance between the centers of 2 propellers must be such that:

where:
L = distance between centers of the propellers
rP = radius of the propeller
D = diameter of the propeller
Therefore:

From our example in the previous section, for:


D = 10 in
N=8
then the length of each arm has to be, at least:
R > 10 in = 11 in
A relatively common choice for copter arms is to use carbon fiber tubes; they are relatively
cheap compared to other drone parts, come in different shapes, can be cut to size (carefully, the fumes
coming from the friction between the saw and the tube are quite toxic) and wiring to the motors can be
protected by passing it through the tubes.
They can be connected to the drone’s body using tube clamps or joints; motors can be mounted to
the tube using motor mounts.
Example: F15738/9 Dia 16mm Multi-Axle Clamp Type Motor Mount Plate Holder,
Hobbypower 3k Cf Motor Mount Set.
Symmetry is very important so using individual arms mounted radially from the frame’s center
can become complicated if using a non-symmetrical frame.
An alternative to consider is setting the arms in an orthogonal configuration. For N = 8 we’d
have a configuration that resembles a hashtag:

For N = 8 and 10” propellers:


L > 10” = 11” (distance between propellers)
d = 7.8” (~ 8”)
This configuration guarantees the propellers will not reach the electronics in the center
(assuming the frame is within the central square); the central square provides 121 sq in of area to place
electronics; it requires only about 64 inches of tubing for the arms; in comparison the radial mount with
8 legs of 14 inches each requires 112 inches of tubing.
An example of this design scheme is this UPS delivery drone model:

Figure 22: UPS delivery drone


(Source: https://h7f7z2r7.stackpathcdn.com/sites/default/files/images/articles/ups-drone-front-0227-1.jpg)

One disadvantage of the hashtag design is that, if the diameter for the actual propeller ends up
to be larger than calculated, it affects the size of the whole UAV frame; in the traditional radial
configuration it only affects the length of the arms.
Finally, aircraft storage and transportation is also a factor to consider. Rigid arms will work,
but storage and shipping may get difficult. One common solution is to use folding arm connectors.
Example: JMT Z16 DIY Aluminum Folding Arm
Legs
Multi-propeller copters usually rely on legs as landing gear. Landing gear can be fixed or
retractable. Retractable landing gear will normally be mounted to retract outwards to avoid physical
contact with the batteries and payload, usually placed under the copter’s body.
Each leg can be divided into 3 core parts: head, body and foot.
Head
The head is the part connected to the copter; the legs can be connected to the copter’s body, to
the copter’s arm or under the motor itself.
The leg can also be retractable, with a folding joint at or near the head equipped with a servo
motor that allows the landing gear to be folded during flight.
Example: powerday Tarot TL65B44 Retractable Landing
Body
The body is the structure of the leg itself; it can come in different shapes, materials and
configurations.
Example: ShareGoo Universal Tall Landing Gear, Mallofusa Universal Landing Gear
Foot
The foot is the part of the leg that touches the ground.
The criteria to select the proper landing gear are:
1. The vertical distance between the head and the foot must be greater than the height of
batteries plus payload
2. The horizontal distance between the head and the foot and mounting position must be such
that the foot is located as far from the body as possible, to improve stability on take-off and
landing
3. The material and structure must be able to support the weight of the UAV

In reality, most - if not all - landing gear and drone legs available in the market are designed for
specific commercial drones. In general, when working with custom drones, custom made legs will often
be required.
This doesn’t mean the legs must be difficult to build and install or expensive; the chapters
dedicated to the UAV design will show a simple, cheap, lightweight and strong way to build a landing
gear for the UAV.
UAV Body
The body is the central part of the aircraft. Here is where the electronics are placed, as well
as batteries and cables connecting the various components among themselves.
Despite the fact that there are hundreds of pre-fabricated form factors for the UAV body
available for a builder to choose from, when building a custom aircraft it may not be possible to find a
suitable one. For example, one will be hard pressed to find an off-the-shelf body that fits the 8 propeller
using the hashtag frame shape.
When selecting the body, the designer must take into account the following aspects:
1. Strength: The material must be hard enough to resist crashes but pliable enough to be
drilled and cut to shape
2. Weight: the material must be as light as possible so it does not compromise the payload
capacity or flight time
3. Surface area: it must provide enough space for mounting all the components in a suitable
distribution.

Propellers
UAV propellers can be made of composite polymeric materials like nylon, fiberglass and
carbon fiber. Carbon fiber propellers are more rigid and lighter, but may be less stable in windy
conditions. It is recommended to use cheaper plastic or fiberglass propellers for testing and validation
of the UAV parameters and functionality and then switch to carbon fiber only if needed.
Propellers can be manufactured to rotate either in clockwise or counterclockwise direction,
when looked from above, with the standard direction being counterclockwise. In general, copters will
use an even number of propellers, half rotating clockwise and half counterclockwise.
Diameter in a 2-bladed propeller is the length of the propeller from tip to tip, while pitch is
defined as the distance traveled by the propeller at one complete rotation.

Flight controller selection


There are many different flight controllers that can be used when building a multi-propeller
copter. This work focuses on flight controllers compatible with PX4 but there are many different choices
depending on the application: racing, filming, inspection, survey, etc.
Here is the current official list of some flight controllers supporting PX4 [26]:

Cont Description
rolle
r
mRo Popular general purpose flight controller (this is a slightly updated version of the
Pixha discontinued 3DR Pixhawk 1).
wk
Pixra Very small/light autopilot optimized for FPV racers. It is suited to any small frame that
cer requires no more than 6 PWM outputs.
Pixha Small general purpose autopilot that has been optimized for ease of setup.
wk The controller has internal vibration damping and only 8 main outputs (no AUX ports),
Mini making it much less daunting to install and connect. It is not suitable for
vehicles/functions that require AUX ports.

Pixha Flexible autopilot intended primarily for manufacturers of commercial systems. It is


wk 2 designed to be used with a domain-specific carrier board in order to reduce the wiring,
improve reliability, and ease of assembly.
Pixha Pixhawk 4 is optimized to run PX4 version 1.7 and is suitable for academic and
wk 4 commercial developers. It features more computing power and 2X the RAM than
previous versions, additional ports for better integration and expansion, new sensors and
integrated vibration isolation.

The following subsections are specific to the Pixhawk 4 running PX4 but all flight controllers
follow similar procedures
Sensor tuning/calibration
PID tuning
There are 3 PID controllers implemented in the PX4 code: roll rate, pitch rate and yaw rate.
The gains for these controllers are:

Parameter Description Ran D


ge ef
au
lt
MC_ROLLRAT Roll rate P gain 0.0 0.
E_P (FLOAT) Comment: Roll rate proportional gain, i.e. control output > 15
for angular speed error 1 rad/s. 0.5
(0.0
1)
MC_ROLLRAT Roll rate I gain 0.0 0.
E_I (FLOAT) Comment: Roll rate integral gain. Can be set to >? 05
compensate for static thrust difference or gravity center (0.0
offset. 1)

MC_ROLLRAT Roll rate D gain 0.0 0.


E_D (FLOAT) Comment: Roll rate differential gain. Small values help > 00
reduce fast oscillations. If the value is too big oscillations 0.01 3
will appear again. (0.0
005
)
MC_PITCHRA Pitch rate P gain 0.0 0.
TE_P (FLOAT) Comment: Pitch rate proportional gain, i.e. control output > 15
for angular speed error 1 rad/s. 0.6
(0.0
1)
MC_PITCHRA Pitch rate I gain 0.0 0.
TE_I (FLOAT) Comment: Pitch rate integral gain. Can be set to >? 05
compensate for static thrust difference or gravity center (0.0
offset. 1)

MC_PITCHRA Pitch rate D gain 0.0 0.


TE_D (FLOAT) Comment: Pitch rate differential gain. Small values help >? 0
reduce fast oscillations. If the value is too big oscillations (0.0
will appear again. 005
)
MC_YAWRATE Yaw rate P gain 0.0 0.
_P (FLOAT) Comment: Yaw rate proportional gain, i.e. control output > 2
for angular speed error 1 rad/s. 0.6
(0.0
1)
MC_YAWRATE Yaw rate I gain 0.0 0.
_I (FLOAT) Comment: Yaw rate integral gain. Can be set to >? 1
compensate for static thrust difference or gravity center (0.0
offset. 1)

MC_YAWRATE Yaw rate D gain 0.0 0.


_D (FLOAT) Comment: Yaw rate differential gain. Small values help >? 0
reduce fast oscillations. If the value is too big oscillations (0.0
will appear again. 1)

There are other PID gains of interest:

MPC_XY_V Differential gain for horizontal velocity error. Small values 0 0


EL_D help reduce fast oscillations. If value is too big oscillations . .
(FLOAT) will appear again 0 0
0 1
5
>
0
.
1
MPC_XY_V Integral gain for horizontal velocity error 0 0
EL_I Comment: Non-zero value allows to eliminate steady state . .
(FLOAT) errors in the presence of disturbances like wind. 0 0
> 2
3
.
0
MPC_XY_V Proportional gain for horizontal velocity error 0 0
EL_P . .
(FLOAT) 0 0
6 9
>
0
.
1
5

As it was studied in the first sections, to properly estimate the gains, follow these steps:
1. Write approximate equations for the physical model for the variable of interest
2. Determine closed loop system and add PID controller
3. Resolve the equation
4. Determine the gains for the desired behavior (fast climb to steady state, low overshoot, etc.)

As an example, let’s resolve for MPC_XY_VEL_P assuming only the proportional controller
Physical model

Very simplified model (linearized drag, simplified applied forces)

Closed-loop system with proportional controller

where:
K = MPC_XY_VEL_P
vD = desired horizontal velocity
v = current horizontal velocity
T = maximum thrust expected from the motors = 2mg (in PX4 the PID gains are used to calculate
percentages of the maxim thrust); maximum thrust is 2x the UAV weight

Resolve the equation

Apply constraints and calculate K


Assume c = 0.5 N x s/m, m = 2 kg, vD = 5 m/s

Here is the procedure:

a. Select a value for K within the allowed range


b. Calculate t for the speed to be 95% of the steady-state speed (steady-state speed is expected
to be less than the desired speed)

Here is a table with some gains selected from the allowed range and the corresponding vD and
time:

Gain (K) Steady-state speed Time (95% steady-state speed)


0.06 4.1 m/s 0.9 s
0.10 4.4 m/s 0.6 s
0.15 4.6 m/s 0.4 s (lowest possible time)

The values for the integral and derivative gains can be calculated following a similar
procedure.
Parameters
This section lists a set of parameters that must be set by hand with values appropriate to the
operation parameters of the application.
MAVLINK

Parameter Value Description


MAV_COMP_ 1 (default value, Component ID
ID no need to change)
MAV_SYS_I 1 (default value, System ID
D no need to change)
MAV_TYPE 35 frame types Frame type
supported. Copters
are:
2: four rotors
13: six rotors
14: eight rotors
35: ten rotors
29: twelve rotors
MAV_0_MOD Either set this to: MAVLink Mode (instance 0)
E 0 = Normal The MAVLink Mode defines the set of streamed messages (for
2 = Onboard example the vehicle's attitude) and their sending rates.

Serial ports
Parameter Value Description
SER_GPS1_BAUD 0: auto (GPS driver discover baud rate Baud rate for the GPS port.
automatically) Pixhawk provides 2 but normally
1 GPS receiver is used
SER_TEL1_BAUD 115200: 115200 8N1; recommended Baud rate for the TELEM 1 Serial
baud rate for sensing telemetry from Port
PX4 as well as receiving MAVLINK Pixhawk provides several serial
messages ports; for interaction with an on-
board computer TELEM 1 is
sufficient
GPS_1_CONFIG 201: GPS 1 port Serial Configuration for Main GPS
Default value, keep it
MAV_0_CONFIG 101: TELEM 1 Serial Configuration for MAVLink
Default value, keep it (instance 0)
TEL_FRSKY_CONF 102: TELEM 2 This is the telemetry port
IG connected to the RC receiver.
No need to setup the baud rate, that
is done automatically by the PX4
driver
Multicopter position control
The parameters described here are relevant for autonomous mode. For the complete list see [28].

Name Description M D U
i ef n
n au it
> lt s
M
a
x
(
I
n
c
r
.
)

MPC_ACC_DOWN_ Maximum vertical acceleration in velocity 2 10 m


MAX (FLOAT) controlled modes down . .0 /s
0 /s
>
1
5
.
0
(
1
)
MPC_ACC_HOR Acceleration for auto and for manual 2 5. m
(FLOAT) Comment: Note: In manual, this parameter is . 0 /s
only used in MPC_POS_MODE 1. 0 /s
>
1
5
.
0
(
1
)
MPC_ACC_UP_MA Maximum vertical acceleration in velocity 2 10 m
X (FLOAT) controlled modes upward . .0 /s
0 /s
>
1
5
.
0
(
1
)
MPC_ALT_MODE Altitude control mode. 0 0
(INT32) 0: Uses altimeter to maintain altitude relative to >
the point of origin; altitude may vary during flight 2
due to sensor drift.
1: Follow the terrain during flight. Needs a
distance to ground sensor (e.g. lidar), Will
fallback to mode 0 behavior if sensor data is
invalid
2: Behaves as mode 1 when hovering and as
mode 0 when moving.
Most use cases will use mode 0.

MPC_HOLD_MAX_ Maximum horizontal velocity for which position 0 0. m


XY (FLOAT) hold is enabled (use 0 to disable check). . 8 /s
Use the default. 0
>
3
.
0
MPC_HOLD_MAX_ Maximum vertical velocity for which position 0 0. m
Z (FLOAT) hold is enabled (use 0 to disable check). . 6 /s
Use the default. 0
>
3
.
0
MPC_JERK_AUTO Jerk limit in auto mode 5 8. m
(FLOAT) Recommended value is between 1 and 2 Gs (~10 . 0 /s
and 20 m/s/s) 0 /s
Comment: Limit the maximum jerk of the > /s
vehicle (how fast the acceleration can change). A 8
lower value leads to smoother vehicle motions, 0
but it also limits its agility. .
0
(
1
)
MPC_LAND_ALT1 Altitude for slow descent 0 10 m
(FLOAT) Below this altitude descending velocity gets > .0
limited to a value between 1
"MPC_Z_VEL_MAX" and 2
"MPC_LAND_SPEED" to enable a smooth 2
descent experience Value needs to be higher than
"MPC_LAND_ALT2"

MPC_LAND_ALT2 Altitude for slow landing 0 5. m


(FLOAT) Below this altitude descending velocity gets > 0
limited to "MPC_LAND_SPEED" Value needs 1
to be lower than "MPC_LAND_ALT1" 2
2
MPC_LAND_SPEED Landing descent rate 0 0. m
(FLOAT) Lower values make the landing smooth but makes . 7 /s
it harder for the controller to detect when the 6
copter is landed. >
Recommended values is 1 m/s ?

MPC_TKO_RAMP_ Position control smooth takeoff ramp time 0 3.


T (FLOAT) constant > 0
Increasing this value will make takeoff slower. If 5
it's too slow the drone might scratch the ground
and tip over. A time constant of 0 disables the
ramp.
Use default

MPC_TKO_SPEED Takeoff climb rate 1 1. m


(FLOAT) Recommended is 3 m/s > 5 /s
5
MPC_XY_CRUISE Maximum horizontal velocity in mission 3 5. m
(FLOAT) Normal horizontal velocity in AUTO modes. . 0 /s
5 m/s is quite fast, the copter will be 1 mile 0
away in 5 minutes; when testing use 2 m/s so the >
pilot can take timely actions in case something 2
goes wrong. 0
.
0
(
1
)
MPC_XY_P (FLOAT) Proportional gain for horizontal position error 0 0.
Estimate using the methods described in the text. . 95
0
>
2
.
0
MPC_XY_VEL_D Differential gain for horizontal velocity error. 0 0.
(FLOAT) Small values help reduce fast oscillations. If . 01
value is too big oscillations will appear again 0
Estimate using the methods described in the text. 0
5
>
0
.
1
MPC_XY_VEL_I Integral gain for horizontal velocity error 0 0.
(FLOAT) Needed for eliminating the steady state error. . 02
Estimate using the methods described in the text. 0
>
3
.
0
MPC_XY_VEL_MA Maximum horizontal velocity 0 12 m
X (FLOAT) Comment: Maximum horizontal velocity in . .0 /s
AUTO mode. If higher speeds are commanded in 0
a mission they will be capped to this velocity. >
The default is good. 12 m/s is 27 mph 2
0
.
0
(
1
)
MPC_XY_VEL_P Proportional gain for horizontal velocity error 0 0.
(FLOAT) Estimate using the methods described in the text. . 09
0
6
>
0
.
1
5
MPC_Z_P (FLOAT) Proportional gain for vertical position error 0 1.
Estimate using the methods described in the text. . 0
0
>
1
.
5
MPC_Z_TRAJ_P Proportional gain for vertical trajectory position 0 0.
(FLOAT) error . 3
Estimate using the methods described in the text. 1
>
5
.
0
MPC_Z_VEL_D Differential gain for vertical velocity error 0 0.
(FLOAT) Estimate using the methods described in the text. . 0
0
>
0
.
1
MPC_Z_VEL_I Integral gain for vertical velocity error 0 0.
(FLOAT) Needed for eliminating steady state error. . 02
Estimate using the methods described in the text. 0
1
>
0
.
1
MPC_Z_VEL_MAX_ Maximum vertical descent velocity 0 1. m
DN (FLOAT) Use 2 m/s since recommended landing speed is 1 . 0 /s
m/s 5
>
4
.
0
MPC_Z_VEL_MAX_ Maximum vertical ascent velocity 0 3. m
UP (FLOAT) Use the default. At this speed the copter will . 0 /s
reach the 400 ft above ground ceiling in 40 5
seconds >
8
.
0
MPC_Z_VEL_P Proportional gain for vertical velocity error 0 0.
(FLOAT) Estimate using the methods described in this text . 2
1
>
0
.
4
PWM outputs

Name Description M D U
in ef n
> au i
M lt t
a s
x
MOT_ORDERI Motor Ordering 0 0
NG (INT32) Specific for certain UAVs that use 1-to-4 ESCs >
Keep the default 0 1

PWM_DISARM Set the disarmed PWM for the main outputs 0 90 u


ED (INT32) Comment: Special values that silences the ESCs or > 0 s
primes it for operation. Value defined by manufacturer 2
2
Reboot required: true
0
0
PWM_MAX Set the maximum PWM for the main outputs. 1 20 u
(INT32) Value will come from the power/current calculations 6 00 s
for the UAV. 0
Reboot required: true 0
>
2
2
0
0
PWM_MIN Set the minimum PWM for the main outputs 8 10 u
(INT32) Comment: Set to 1000 for industry default 0 00 s
0
Reboot required: true
>
1
4
0
0
PWM_RATE Set the PWM output frequency for the main outputs -1 40 H
(INT32) Comment: Set to 400 for industry default or 1000 for > 0 z
high frequency ESCs. Set to 0 for Oneshot125. 2
The project in this book uses Oneshot125 so set this 0
parameter to 0 0
0
Reboot required: true

PWM_SBUS_M S.BUS out 0


ODE (INT32) Comment: Set this to 1 for the project in this book
Sensor position

Name Description M D U
i ef n
n au i
> lt t
M s
a
x
SENS_BOARD_ Board rotation 0 0
ROT (INT32) This parameter defines the rotation of the FMU board >
relative to the platform; rotation is clockwise when 3
looking from above. 4
Each possible value maps to a different combination of
yaw, pitch and row.
0: No rotation
1: Yaw 45°
2: Yaw 90°
3: Yaw 135°
4: Yaw 180°
5: Yaw 225°
6: Yaw 270°
7: Yaw 315°
8: Roll 180°
9: Roll 180°, Yaw 45°
10: Roll 180°, Yaw 90°
11: Roll 180°, Yaw 135°
12: Pitch 180°
13: Roll 180°, Yaw 225°
14: Roll 180°, Yaw 270°
15: Roll 180°, Yaw 315°
16: Roll 90°
17: Roll 90°, Yaw 45°
18: Roll 90°, Yaw 90°
19: Roll 90°, Yaw 135°
20: Roll 270°
21: Roll 270°, Yaw 45°
22: Roll 270°, Yaw 90°
23: Roll 270°, Yaw 135°
24: Pitch 90°
25: Pitch 270°
26: Roll 270°, Yaw 270°
27: Roll 180°, Pitch 270°
28: Pitch 90°, Yaw 180
29: Pitch 90°, Roll 90°
30: Yaw 293°, Pitch 68°, Roll 90° (Solo)
31: Pitch 90°, Roll 270°
32: Pitch 9°, Yaw 180°
33: Pitch 45°
34: Pitch 315°

Additional components
This session covers the electronic components that, although not directly involved with flight,
are however fundamental for the proper functioning of the aircraft.
GNSS antenna/receiver
The UAV will not be able to maintain stable autonomous flight without a precise way to
determine its location. Without using optical flow cameras, stereoscopic cameras, lidars, sonars or other
sensors that allow the UAV to determine its position, stable flight is not possible.
Obviously, the simplest and most cost effective way to do so, at least for outdoor applications,
is via GNSS.
It is highly recommended to place the GNSS receiver away from the propellers and other
electronics to avoid radio-frequency and mechanical interference (signal multipath, reflection, etc.). For
that the builder will want to use a GPS antenna mount holder for the receiver; one usually comes with
the GPS receiver.
Ideally the holder is mounted as close to the center of the aircraft since the position is always
calculated relative to the antenna/receiver. This arrangement is, however, prone to damage in case of an
accident.
Alternatively, the developer can also cover the electronics with an RF blocking hard top and
then mount the receiver directly on top of it.
The GPS output is connected to the GPS 1 port in the Pixhawk.
Example: Holybro Pixhawk 4 GPS receiver (Ublox M8N), Ublox Neo-M8N GPS with
Compass, mRo GPS u-Blox Neo-M8N Dual Compass LIS3MDL+ IST8310, Drotek uBlox
GPS/Compasses, Holybro Micro M8N GPS Module, Holybro Ublox NEO-M8N GPS Module, Here
GNSS GPS (M8N), Zubax GNSS 2

Real-Time Kinematics (RTK) board


If high-precision location is required, RTK is one solution that technically works well for
UAVs. It is not fundamental for an UAV operation and it suffers from the same limitations of GNSS - for
example, can’t be used indoors - but it is relatively cheap when compared to the price of other high-
precision sensors.
Another drawback of RTK is that it requires at least one fixed base station in a known
location, transmitting correction data to the UAV. Fortunately, a few companies are launching RTK
services nationwide, starting in 2020.
Correction data - RTCM - is directly supported by PX4 via MAVLINK message
GPS_RTCM_DATA sent over the traffic channel - usually WiFi - from QGroundControl to the UAV; also
PX4 only supports the UbloxM8P receiver for RTK so the solution is limited.
Another solution is to use an external RTK module or receiver, as follows:
1. Connect the RTK receiver UART output to the GPS 1 input in the flight controller
2. Connect the RTK receiver input to a UART output in the on-board computer
3. Connect a passive GNSS antenna to the GNSS input connector in the RTK receiver
4. Connect the on-board computer to the mobile network

In this configuration:
1. The on-board computer gets RTCM data via mobile network
2. The on-board computer pushes RTCM data to the RTK receiver via UART
3. The RTK receiver calculates the location using the correction data
4. The RTK board pushes location to the flight controller via UART output/GPS 1 input

This configuration is extremely flexible since it is very loosely coupled - in terms of hardware -
to the RTK service and RTK receiver providers the work is almost 100% done by software. Most, if not
all, RTK receivers can be configured to receive RTCM data via UART interface.

Figure 23: EmlidTM Reach M+ and Reach M2 RTK receivers


(Credit: https://emlid.com/wp-content/themes/emlid/img/reach/reaches.png; image used under permission)

Radio control receiver


Federal Aviation Agency regulation part 107 requires the UAV to have a remote pilot in
command.
In other words, until the FAA allows for beyond line of sight flight, it must be possible for a
remote pilot to take over control of the aircraft in case something goes wrong with the autonomous
operation of the drone. This is analogous to regulation that requires a human driver behind the wheel of
an autonomous vehicle.
In addition to that, QGroundControl requires a radio to be connected and calibrated before any
other calibration can be performed.
The FrSky TARANIS X9D with the X8R receiver is a popular combo and is used in the
project detailed in this book, but there are others like Futaba and Spektrum that can also be used.
The radio must be calibrated so PX4 can understand how to properly interpret the commands
from the radio transmitter [37]. In addition, XD9 switches can be configured to change flight modes;
follow the instructions in [38] to map different flight modes to different channels.

Cellular modem
The cellular network - in particular 4G and 5G technologies - is a suitable option for
telemetry and command/control of UAVs; it has excellent coverage, high throughput, low latency and
lower cost if compared to other forms of communication (e.g. satellite).
USB powered hub
All cellular modems - with rare exceptions that use the Ethernet port - will connect to the on
board computer using a USB port and be powered by it. Depending on the selected model, the modem
can pull a relatively high current and there is a good chance the USB port in the on-board computer will
not be able to supply it.
One possible solution is to use a USB hub with external power input. The power is supplied
to the modem via the hub.
Another option is to use a WiFi mobile hotspot that provides WiFi connectivity to the mobile
network; the hotspot can be powered directly by the voltage regulator and the on-board computer can
connect to it using a WiFi USB dongle. A mobile carrier data plan will be required to use a mobile
hotspot.
Some hobbyists use an actual cell phone for connectivity. There are many options in the market
that can be used to tether the on-board computer to the Internet. However, phones are quite expensive
and fragile; in a crash they can be permanently damaged.

Voltage regulators
As it was mentioned before, the voltage provided by the LiPo batteries commonly used in
UAVs are integer multiples of 3.7 V; this means that, in almost all cases, it is not possible to provide the
correct voltage to the electronic components on board of the aircraft.
Electronics commonly work under a few well-defined voltages: 3.3 V, 5 V and 12 V. In order
to obtain these voltages from the LiPO batteries one needs to resort to voltage regulators.
A voltage regulator will take a range of input voltages and provide a stable output voltage at a
level defined by the developer.
Here is a list of regulators that will provide the necessary power for the on-board computer,
the flight controller, the RC receiver and the GPS/RTK receiver as needed.

Component Voltage Current


Pixhawk 4 (sensors and comm ports) 4.1 - 5.7 V 2.5 A (max.)
On-board computer ~5 V 6 A (max.)
RTK board ~5 V 1.5 A (max.)
Cellular modem ~5 V 3A
Radio control receiver 4.0 - 10 V 0.1 A
Total current ~13 A

In order to reduce the hardware on board of the aircraft, a step-down voltage regulator that
covers a wide range of input voltages as well as providing enough current for all components is
recommended. The YEP 20A HV (2~12S) SBEC w/Selectable Voltage Output is an example of such a
regulator.

Power distribution
After all calculations are done, the size of the UAV is defined, the materials and components
selected, it is time to place them on the UAV and connect them. And this is more complicated than it
looks.
Providing power to all the components requires some careful planning. In the 8 propeller
design, the 2 batteries must provide power to the voltage regulator and 8 ESCs.
A convenient way of doing this is to use a power distribution board (PDB) or a power
management board (PMB).
PDBs and PMBs designed specifically for UAVs provide connectors that are conveniently
positioned to optimize the wiring and can withstand the high current levels associated with copter
operation.

Figure 24: Holybro Pixhawk 4 Power Module (PM07)


(Source: https://docs.px4.io/master/assets/img/pm07_hero.9e91892c.jpg
Credit: © PX4 Dev Team. License: CC BY 4.0, via Wikimedia Commons)

Figure 25: CUAV HV power module


(Source: https://docs.px4.io/master/assets/img/hv_pm.4b8b413c.jpg
Credit: © PX4 Dev Team. License: CC BY 4.0, via Wikimedia Commons)

It is also recommended installing a pair of power distribution bars as a way to organize the
wires coming from the battery into the power modules and electronics, for live power and ground.
Power distribution bars can handle over 150A and are commonly used in the automotive and maritime
industry.
5V distribution
For distribution of the 5 V power to some of the electronics, using splice wire terminals is a
good, inexpensive solution for connecting the power cables to the power terminals. The Nilight -
50004R 120 Pcs/60 Pairs Quick Splice Wire Terminals T-Tap Self-striping Kit is a very convenient
solution for currents up to 20 A, within the ranges used by ESCs and electronics.
Battery connectors
Batteries come with different types of connectors, specified for different current levels.
Here is a list of battery connector types and their specifications:

1 - 10 A 30 - 70 A 70+ A
Molex Deans or T Plug EC5
JST EC3 XT90
Deans XT60 Anderson Power Pole
Servo TRX Bullet Style
XT30 XT150
EC2 AS150

Batteries sporting either the XT60, XT90 or XT150 connectors are recommended for the
currents expected to be drained from each battery.
Battery charger
A good battery charger is an essential piece of equipment. TheEV-Peak CQ3 Multi Charger
4x 100W NiMH / LiPO with Built-in Balance is a good model, it supports different battery sizes and
types and can charge up to 4 batteries simultaneously.
Normally LiPo charges require a balance cable or board, so it can read status from the
battery. The HobbyStar JST-XH Balance Board Adapter is an example.
A set of banana plugs for the selected connector size is also needed for connecting the
batteries to the charger. Make sure the cables have the connectors with the right size for the battery
connectors.
Power module
It is highly recommended to have a power module installed in the UAV and connected to the
flight controller. In fact, it is not possible to do automatic ESC calibration without one connected to the
flight controller.
It is important to note that the power module is not a replacement for the voltage regulator; for
example the PM07 has a 3A limit in the 5V output so it can only power the Pixhawk through that output.
The voltage regulator is still needed for power to the on-board computer and other electronics on board
the UAV.
Details on the use and operation of the PM07 can be found here [32]
Power cables
Connecting power to the various electronic devices on board of the UAV can be challenging.
Many of the off-the-shelf devices are designed to be powered by bulky wall chargers not suitable for
this application.
Fortunately, if the reader uses the electronic components recommended in this book, all
electronics - except for the flight controller, powered by its own cable through the power module - are
powered using micro-USB or USB-C cables. It is relatively easy to find USB-C and micro-USB portal
cables for power only in the market; if not any USB cable can be cut and trimmed to serve this purpose.
When selecting the cables that connect the batteries to the power modules, pay close attention
to the currents expected to be consumed by the UAV For each current level and wire length, a cable with
the appropriate gauge is required in order to avoid overheating and even fire.
The table below summarizes the current limits for typical wire gauges used in UAVs.

Wire gauge Purpose Maximum safe current


(AWG) (A)
6 Connect power distribution bars to power module 100
10 XT90 pigtail from battery to power distribution bar 50
12 XT60 pigtail from battery to power distribution bar 30
18 ESC/motors 15
26 - 28 Electronics 1.5 - 3

Summary
There are many variables that affect the design of a UAV.
A systematic procedure was presented for determining the size of all required parts.
Nevertheless, sound estimates for several variables are required to make the calculations
possible; in that case, always try to overestimate the parameters. Overpowered drones are safe;
underpowered are a menace.
Be wary of the limits of physical models; they must be used to calculate a ballpark for the
necessary values. Always refine the calculations, once more data is available, in particular using
propeller and motor data from manufacturers.

Problems
1. Using the drone calculations spreadsheet, find a configuration that can fly for 30 minutes,
using the following constraints:

Frame weight (WF): 1500 kg


Payload (WP:) 1000 kg
Number of motors (N): 4
Number of batteries: (n) 1
Voltage for electronics (VE): 5 volts
Chapter 7 - Command and control
software
Objectives
This chapter covers a client application and proxy server that
allow QGroundControl to communicate with the UAV through the on-board
computer and using the mobile network.

Software description
This section describes in detail the simplest client/server
application that can be implemented in the on-board computer that allows
command and control of a UAV over mobile cellular networks.
As is, this system is not feasible for a practical commercial
application since it requires several manual setup steps, only supports one
UAV at a time and provides no security or privacy features; however, it can
be used as a basis for one.
The source code is open source and available here, along with the
executable binaries.
The client application assumes that the on-board computer is an RPi4
running the Raspberry OS; this constraint is due to dependencies on the GPIO
configuration for the serial port; if a different on-board computer is used the
client must be modified and recompiled accordingly.
The functionality described here is not even close to everything
that can be done with software in an on-board computer. That software can
be as complex as an UAV with a powerful, AI enabled, on-board computer
using machine learning and computer vision to determine damage in a house
after a storm and autonomously deciding where to go next.
The system described here requires the following:
1. Laptop or tablet connected to the Internet (cable, WiFI, mobile)
2. Pixhawk with the latest PX4 firmware
a. Firmware can be updated by connecting Pixhawk to the
PC via USB and using QGroudControl to update the
firmware
b. The laptop/desktop must be connected to the Internet so
the new firmware can be downloaded.
c. Pixhawk must be powered solely by the PC’s USB port.
3. UAV with on-board computer connected to the flight controller
a. Again, the implementation assumes RPi 4 for the on-
board computer and Pixhawk running PX4; if a different
on-board computer is used the software must be modified
and re-compiled as needed.
4. QGroundControl installed in the laptop
a. QGroundControl will be used to send commands to the
UAV and receive telemetry
b. Use version 4.1.1 or later.
5. A free account with a hosting service like Amazon’s’ AWS or
RedHat’s OpenShift
a. Must allow running standalone software, not only web
pages
b. Must support running programs in Java
6. The server software running in the hosting server (need a Java
Runtime installed)
7. The client software running in the on-board computer (need a Java
Runtime installed)

The software assumes the on-board computer is connected to the


TELEM 1 port in the Pixhawk via the RPi 4 primary UART serial port.

Setup
1. Upload and run the server software in the server

The server software is a simple proxy that will route messages


from QGroundControl to the UAV and vice-versa.
In general, hosting services like AWS and OpenShift will provide
a dashboard where the user can open up TCP/UDP ports for external access.
Make sure the port numbers used when starting the server are open.
2. Connect the RPi 4 primary serial port to the Pixhawk TELEM 1
port
a. Pin 2 from TELEM 1 (TX) in PIxhawk to pin 10 in RPi 4
(RX)
b. Pin 3 from TELEM 1 (RX) in PIxhawk to pin 8 in RPI 4
(TX)
c. Pin 6 from TELEM 1 (GND) in PIxhawk to one of the
ground pins in RPi 4 (6, 9, 14, 20, 25, 30, 34, 39)
3. Connect the on-board computer to the Internet, preferably using the
cellular modem that will be used with the UAV, so the RPi 4
automatically connects to it on power up.
4. Download and run the client application in the RPi 4, following
the instructions on the README page. Optionally, here are
instructions on how to set up the RPi 4 so the client app starts
automatically on boot up.

The client application does 3 things:


a. Connects to the server over the cellular modem, once Internet
is available
b. Connects to the Pixhawk’s TELEM 1 via serial port. See
details here on how to configure the Raspberry Pi 4 serial
port
c. Sends messages received from QGroundControl through the
proxy server to the flight controller and telemetry read from
the flight controller back to QGroundControl, also through the
proxy server

3. Configure QGroundControl to communicate with the server

See details in here, in the Appendix.


Chapter 8 - UAV Project
Objectives
In this chapter, the formulas, methods and algorithms described in
the previous chapters will be used to design a UAV from scratch.

Process
In order to use the algorithm previously described, one of the first
steps is to estimate the weight of the aircraft, without payload.
This is a little tricky because the weight depends on how many and
size of motors and propellers, but the motors cannot be determined until the
weight is known.
On top of that, the calculated diameter and RPM for the required
thrust and power will not match exactly the numbers from the manufacturer.
Here is the general flow:
1. Start with an initial educated guess for the weight of the UAV
(without batteries)
2. Using the drone selection spreadsheet [24], calculate the
propeller’s diameter and pitch, and the motor’s kV, using an
arbitrary number of batteries and propellers
3. Select a suitable configuration (e.g., based on flight duration or
propeller size)
4. Find a propeller with diameter and pitch around the calculated
values, and obtain the actual power, thrust and RPM combination
that match the required constraints for the UAV
5. Find a motor with kV around the the calculated value
6. Re-calculate the total weight of the UAV using the actual weight of
motors and propellers
7. Use the values from the selected propeller, motor and final weight
in with the drone calculation spreadsheet [24] and determine if the
results are still acceptable
8. If the results are not acceptable, start again using the new weight
estimates.
Weight estimate
The weight estimate will be an educated guess. In the bill of
materials provided in the next section, the weight of the components to be
used in the project is provided. From that table:
1. Electronics: 500 g
2. Arms, body, joints, landing gear: 1200 g
3. Motors: 1200 g (150 g per motor; assuming 8 motors)

In total, about 3 kg for the UAV without any payload and batteries.
As a rule of thumb, assume the payload to be no more than 50% of
the UAV weight. Remember, the battery’s weight is not taken into account in
this initial estimate so it is necessary to leave some room for it.
Propeller and motor parameters
Using the drone selection spreadsheet [24] with the following
constraints:
● 2 batteries
● 8 motors
● 3,000 g for frame weight
● 0 g fo payload
● 50 A per battery (WT90 connectors with 10 AWG wiring)
The design will use the output in row 20 of the spreadsheet as the
basis for the next steps:
● 2x Battery:
○ 6S1P
○ 10000 mAh of capacity
○ 1319 g of weight
○ 185 x 70 x 47 mm
○ 20 C discharge rate (444 A)
● 8 x Propeller:
○ 2 blades
○ 13 inches diameter
○ 6.5 inches pitch
○ At least 3.09 lbf (1310 g) of thrust at 6000 RPM
○ Maximum 0.350 HP of power @ 6000 RPM
● 8 x Motor:
○ 278 kV
○ Maximum 6154 RPM at full throttle
○ Maximum 260 W of electrical power at full throttle
● ESC
○ 12 A or more @ 22.2 V
Using this configuration, the uAV is predicted to hover for about 20
minutes, using about 1.3 kW of power at 4400 RPM.

Propeller selection
The design will use APC propellers. These are cost-effective,
good quality fiberglass composite propellers, designed specifically for
electrical motors.
The design spreadsheet recommends a 13 x 6.5 propeller, but
looking at the APC propeller specification the 12x6 seems to provide the
necessary thrust within the power limits, if a motor with a somewhat higher
kV is used. From the APC performance data [33] for these propellers:
● APC 12x6E (standard rotation, counterclockwise)
○ Thrust
■ 3.184 lbf @ 7000 RPM
■ 1.615 lbf @ 5000 RPM
○ Power
■ 0.240 HP @ 7000 RPM
■ 0.091 HP @ 5000 RPM
● APX 12x6EP (reverse rotation, clockwise)
○ Thrust
■ 3.186 lbf @ 7000 RPM
■ 1.616 lbf @ 5000 RPM
○ Power
■ 0.240 @ 7000 RPM
■ 0.091 HP @ 5000 RPM
The shaft diameter is 1/4”; with an adapter ring it will fit motors
with 1/8", 4mm, 5mm, 6mm and 5/16" shaft diameter. The center hub is 23.32
mm (0.8”) in diameter and 10.4 mm (0.41”) high.
Motor selection
Motor selection is more complicated than propeller:
1. Low kV motors are designed to provide high torque, and therefore
are heavier, larger motors, potentially outside the range assumed in
the design
2. High kV motors are lighter and can provide very high RPM, but
will pull more current to provide the RPM and power required by
the design, potentially going over the safety constraints.

For example, assuming the 101 W required to rotate the propellers at


5000 RPM for hovering, as calculated in the spreadsheet (values are
approximated):
● Motor with kv = 330
○ Voltage @ 5000 RPM: 5000/330 = ~ 15 V
○ Current @ 101 W: 101/15 = ~ 7 A => matches the design
requirements
● Motor with kv = 1400
○ Voltage @ 5000 RPM: 5000/1400 = ~ 4 V
○ Current @ 101 W: 101/4 = ~ 25 A => current is way too high
● Motor with kV = 150
○ Maximum RPM @ 22.2 V: 22.2*150 = 3300 RPM => below the
minimum 5000 RPM necessary for hovering
So it is important to select a motor with kV that is as close as
possible to the design requirements, but still within the weight range.
Another very important aspect to consider is how the propeller
attaches to the motor and the diameter of the shaft.
The selected motor is the T-Motor MN4014 kV330 [34]. It weighs
150 g and comes with adapter nuts suitable for attaching the APC propellers.
The 4 mm shaft also works with the APC 12x6E/EP with the
appropriate adapter ring.
Frame dimensions and materials
As previously discussed, the design proposed in this book will use
a frame shape resembling a hashtag.
For the actual body, a square, clear sheet of polycarbonate will be
used. Polycarbonate is cost-effective, very lightweight (about half the weight
of glass and about 13% lighter than PVC) and high impact resistant. It is also
a dielectric, which means it has very little effect on radio propagation. Using
a clear sheet will help make sure the components mounted underneath the
body are correctly positioned, as well as the wiring is properly routed. The
only drawback of using polycarbonate is that drilling requires drill bits for
acrylic, otherwise the sheet can crack.
The arms will be built using circular carbon fiber hollow tubes.
Carbon fiber is well known for its high resistance and low weight. Hollow
tubes allow wires to reach the motors through the tube, keeping the built
clean and safe, and minimizing exposed wires.
It is recommended to use fabric roll wrapped tubing; these types
of tubes provide good stiffness against both bending and compression, since
each layer of fabric is oriented at 90 degrees of each other along the length of
the tube.
The diameter for each tube is selected to fit the foldable joint
support and the motor mount plate; for the selected joint model the tube must
have an outer diameter around 16 mm.
A tube with about 1.6 mm wall will support longitudinal weights
between 4,000 and 6,000 lbs, more than enough for this application.
Finally, the motor mount plate F15738/9 Dia 16mm Multi-Axle
Clamp Type Motor Mount is a good quality, cost-effective motor mount plate,
also suitable for circular carbon fiber tubes with 16 mm diameter.
The foldable joints will be mounted near the corners of the
polycarbonate sheet which require about 20 mm2 to be mounted, so adding 2
extra inches to the length of the square’s side gives enough room for the joints
without them being too close.
Remember that, for the hashtag configuration, the formula for each
arm length is:
where:
D = distance between propellers
L = arm’s length
For this design, the propeller has a 12 inches diameter, so D must
be at least 13 inches so there’s enough space between propellers.
Therefore, for D = 13 in, the arm’s length is 9.2 in (233.5 mm).
However, this length includes the foldable joint and the motor mount plate.
The foldable joint contributes 2.5” to the arm’s length, due to their length and
position where they are mounted, while the motor mount plate contributes
another 2”. Therefore, the actual carbon tube length is about 5” long.
Putting the numbers together, the frame is composed by:
● 1 x square polycarbonate sheet: 17 in x 17 in x 1/16 in
● 8 x carbon fiber tubes: 127 mm x 16 mm x 16 mm each (0.625” outside
diameter, 0,500” inside diameter)
● 8 x JMT Z16 DIY Aluminum Folding Arm Tube Joints
● 8 x F15738/9 Dia 16mm Multi-Axle Clamp Type Motor Mount
Landing gear/legs
As discussed before, finding commercial landing gear or legs for custom drones like this is
difficult, especially for large UAVs.
On the other hand, the UAV designed in this book does not carry any payload, so it does not
have to be very high above ground; in principle, the UAV can lie on the batteries mounted under the
body.
The main issue is that the surface of the batteries is not perfectly flat and the UAV may not be
perfectly balanced; in that case, it is possible for a propeller to hit the ground during takeoff; the role of
the landing gear or legs here is to simply make sure the UAV is sitting flat and sufficiently away from the
ground during takeoff.
The solution used in this project is extremely lightweight and cheap. The design uses 2 19” L x
4” diameter sections of a solid pool noodle, placed along 2 opposite sides of the UAV and firmly
strapped to 2 arms using straps or belts. Straps are used so the legs can be removed when folding the
arms.
This is the supersized, DIY version of a similar solution used in the DJI Mavic 2 Water
Landing Leg.

Wiring
The UAV may consume around 100 A during flight, while each motor may consume about 7 A
each.
Therefore, here is the wiring gauge required for powering the motors:
● Batteries:
○ Connector: XT90
○ Wire: 10 AWG
● ESC
○ Wire: 18 AWG
It is a good idea to avoid loose cables in an UAV, considering that they can interfere with the
propellers during flight. It is recommended the use of self-adhesive wire clips to route the cables and
keep them in place, flush to the aircraft body.

Bill of materials
At this point all required elements for building the UAV are defined and calculated.
Below is a list of all components needed to build the octocopter designed in this text, along with
prices from specific providers and weight for each component.
A blueprint for the UAV assembly is also provided, with the suggested position of each
component and the associated wiring.
All components are attached to the UAV using heavy duty hook-and-loop fasteners (e.g.
Velcro) so they can be easily replaced if needed but will still be firmly positioned during flight.
UAV components
Component Price (USD) Weight Dimensions
(g) (mm)
(W x L x H)

1 x Pixhawk 4 kit $ 211.00 (includes cables for 16 g 44 x 84 x 12


connection to power module
and X8R receiver)
1 x Raspberry Pi 4 $ 30.00 - $ 65.00 (depending 66 g 85 x 56 x --
on memory)
1 x GPS/compass receiver and mount included with Pixhawk 4 kit 32 g 50 x 50 x 4

1 x X8R receiver $ 37.00 17 g 47 × 27 × 15


1 x Power Module (PM07) included with Pixhawk 4 kit 40 g 68 x 50 x 10
1 x Verizon Jetpack® MiFi® 8800L $ 200.00 152 g 67 x 109 x 18
2 X USB Type C power pigtail cable $ 10.00 each = $ 20.00 N/A N/A
1 x YEP 20A HV (2~12S) SBEC $ 25.00 42 g 57 x 26 x --
8 x FVT LITTLEBEE Little bee $ 85.00 (8 pcs bundle) 9g 35 x 17 each
BLHeli_32 SUMMER 30A ESC 2-6 S each =
72 g
1 x Polycarbonate sheet $ 100.00 355 g 406.5 x 406.5
x 1.5 (17 x 17
x 1/16 in)
8 x round carbon fiber tubes (7” long) $50.00 (48” long tube, to be 14 g 127 x 15.8 x
cut in 8 pieces 5” long) each = 15.8 (1.6 mm
112 g wall)
ID = 0.5”
Wall thickness
= 0.0625”
8 x JMT Z16 DIY Aluminum Folding Arm Tube Joint $ 9.00 each = 55 g 68.5 x 18 x 28
$ 72.00 each = (mounting
440 g area is 20 mm
x 18 mm)
1 x Workoutz Jumbo Foam Roll Log 4" $ 30.00 500 g 483 x 101 x
W x 60" L (after 101 (19” x 4”
cut to diameter)
size)
2 x Turnigy High Capacity 10000mAh 6S $ 95.00 each = $ 190.00 1320 g 182 x 77 x 48
12C Lipo Pack w/XT90 each =
2640 g
2 x 6 Terminal Bus Bar - 150A BusBar $ 12.00 each = $ 24.00 63 g 120 x 20 x
Block with Cover each = 42.6
126 g
2 x Tarot FY680 Foldable Battery Mount $ 10.00 each = $ 20.00 26 g 153 x 65 x --
Plate Central Plate (optional) each =
52 g
1 x GH1.25 Cables and connectors Wire $ 9.00 N/A N/A
for Pixhawk2 Pixhawk 4 Pixracer (used to connect the RPi 4
PXFmini Edge CUAV V5 serial pins to the TELEM 1
port in the Pixhawk)
4 x APC B13x6.5E and 4 x APC $ 5.00 each = 26 g 305 mm (12
B13x6.5EP propellers $ 40.00 each = in) diameter
208 g
8 x Tiger Motor MN4014-11 330kv $ 97.00 each = 150 g 58.8 x 58.8 x
$ 776.00 each = 25
1200 g
4 x M6 CCW propeller adapter $ 10.00 each = $ 40.00 N/A N/A
8 x F15738/9 Dia 16mm Multi-Axle $ 9.00 each = $ 72.00 25 g
Clamp Type Motor Mount (4 x black, 4 x red) each =
200 g
Totals: ~ $ 2,100 ~ 6000
g

The final weight is about 500 g higher than estimated, with a corresponding decrease in flight
time, now expected to be 17 minutes instead of the original 20 minutes. For this design, this reduction is
acceptable and the calculations are considered complete at this point.
If this reduction in flight time is not acceptable, the designer must then go back to the
spreadsheet, put the new weight and recalculate; as indicated before, the process is iterative and it may
take a few rounds before an acceptable configuration is found.
Other materials and tools
This section list the extra materials and tools required for building the UAV:
● Soldering iron, wire and flux
● Wire cutter/stripper
● Cable crimper for wire lugs
● Voltmeter/amperemeter/resistometer (for checking wire connections)
● XT90/10 AWG pigtail cables
● 6, 10 and 18 AWG wires
● Power drill
● Drill bits for acrylic
● Electric saw (handheld or table)
● Mask (due to toxic fumes/particles created when cutting carbon fiber tubes)
● Heavy duty hook-and-loop fasteners
● Taranis X9D RC controller
● Mouse, keyboard, monitor, HDMI cables, etc. (for interaction with RPi 4)
● Screwdrivers, Allen keys, wrenches (different sizes)
● Zip ties of different lengths and sizes (15”, 5”, 3”)
● 2 x 50 amp toggle switch (optional)
● 1 x Nilight - 50004R 120 Pcs/60 Pairs Quick Splice Wire Terminals T-Tap Self-stripping
● Wire lugs for 10 and 6 AWG wires (sizes M4 and M6)
● Wire connectors (multiple gauges)
● Copter landing pad (optional)
● Male JR plug wire extensions (12”)
● EV-Peak CQ3 Multi Charger 4x 100W NiMH / LiPO with Built-in Balance
● Little Bee ESC USB Linker Programming Tool (Silabs)
Blueprint and instructions
This section presents the blueprint [35] for the UAV calculated in
the previous sections.
The blueprint indicates where each component is positioned, as
well as the wiring routes. Some drilling will be required for mounting the
battery holder and arm joints.
When following the blueprint, pay close attention to the position
and wiring of ESCs and motors; the position and corresponding PWM output
of each motor is essential for the proper operation of the UAV. Each ESC
must be properly connected to the motor, so it will rotate in the correct
direction, according to the indications in the blueprint. Remember, the
normal direction is counterclockwise (CCW).
The components are located where they are to facilitate connection
between components and to balance the weight distribution.
Instructions
Work area

1. Large table for the tools and materials


2. Close by outlets to power the tools, battery chargers and other
components
3. If possible, use electrostatic discharge (ESD) protection (e.g.
anti ESD mat, ESD grounding heel strap)
Preparation

1. Using a marker, draw on the polycarbonate sheet the position for


each component, as well as each hole to be drilled
2. Take advantage of the clear polycarbonate sheet and position the
foldable joints under their position on the sheet to make sure the
holes are properly aligned with the foldable joints mounting
screws
3. If using battery mount plates, put them underneath the clear sheet
and mark the holes for the mounting screws, making sure they do
not interfere with the electronics
ESC configuration
This is probably the most time consuming and hardest part when
assembling the UAV, so allocate a couple hours for this activity. The steps
below assume a Windows PC where the app will be downloaded to. There’s
support for other platforms for the 32-bit version of the LIttleBee ESC as
well as via the BLHeli Configurator app for Chrome browser.
Steps 2 and 3 must be executed for all ESCs.
Step 1: Download the BLHeli Suite

1. Download the latest BLHeli Suite from here


a. For the LittleBee Spring make sure the BLHeli_S version
is used; if using the LIttleBee Summer than use the
BLHeli_32 version
2. Extract the ZIP file to a folder (by default it will be
BLHeliSuite<version>
3. Connect the programmer to a PC USB port
Step 2: Connect the ESC, programmer and PC

1. Connect the JR connector from the ESC to the 3 pins in the


programmer
2. Power the ESC on using the 6S battery; make sure to connect the
wires correctly (red to red, black to black)
3. Open the Windows Device Manager
4. Look for the COM ports configuration and write down the COM
port associated to the programmer (this will be needed later for
the BLHeli Suite)

Step 3: ESC flashing and programming

1. Go the app folder and run BLHeliSuite


2. Click on the Select ATMER/SILABS interface tab and select
option C - SILABS BLHeli bootloader (USB/Com)
3. Click on the ESC Setup tab and select Read Setup From Hex File
4. When the dialog opens, select the following using the dropdown
menus:
a. NNNN => MULTI (for multi-motor copter)
b. Flash To: => FVT LIttlebee 30A
5. Select the only item in the dialog and click OK. It will go back to
the main screen
6. At the bottom left of the screen, find the Port: dropdown box and
select the appropriate COM port for the USB programmer (the
same COM port detected in Step 2)
7. Click Connect. If everything was done correctly, the application
will now be connected to the ESC and the 2 indicators next to the
Read Setup button will flash
8. (Optional, only if the firmware is outdated) Click on Flash
BLHeli button, at the bottom of the screen, wait until the
application indicates the flashing process was successful.
9. Click Read Setup to retrieve the current configuration from the
ESC
10.
Make sure the following attributes are set as
indicated:
a.
Motor Direction: Normal and Reversed (equal number of
each)
i. It is highly recommended to mark the
reversed and normal ESCs; for example, using
a non-erasable marker and write “N” or “R” on
the ESC
b. Demag compensation: Off (other values will cut
power to the motor if needed; only enable if the motor
stutters when changing throttle)
c. PWM Frequency/Damped: Damped Light
d.
Enabled PWM Input: Off (this enables OneShot125)
i. May not be present in some versions
e. Startup beep volume: Off (turns off the ESC beep
when it is powered up)
f.
Beacon volume: 1 (lowest possible volume)
i. Some versions allow for it to be turned off
g.
Beacon delay: Infinite (will prevent the ESC to start
beeping if motor is idle for too long)
i. If beacon volume is set to OFF this control is
disabled
11. Click on Write setup at the bottom of the main screen
to push the configuration to the ESC

One more comment before moving to the next section. The BLHeli
Setup tool offers a tab called Motors, which allows testing if the ESCs are
properly programmed. The builder can connect motors to the ESCs, power
them up with the battery, and use the slides to see if they are spinning
properly and as expected.
This step is optional, but recommended. Finding out the ESCs are
not properly configured after mounted in the drone, along with the motors,
will be a major hurdle to the assembly process.
ESC connection to motors
Connection to the motors is both straightforward and tricky.
The 3 wires from the motor must be connected to the 3 plates in the
ESC, in the exact same order, as indicated in the figure below.

Figure 26: Motor connection to the ESC


The T-Motor models are designed to rotate in the standard
counterclockwise direction when connected as displayed in Figure 26, since
this is considered the standard direction of rotation of propellers. Therefore,
the ESCs marked as “N” will be connected to the motors expected to rotate
counterclockwise, while the ones marked “R” will be connected to the
clockwise motors.
Mounting motors and ESCs
Because the motor wires are quite long - around 21” long - and the
ESCs are not - around 2” and 3” long -, and easy access to the ESCs may be
required in case they have to be re-programmed after installation, it is
recommended to mount them underneath the UAV body.
Step 1: Label the motor wires and ESC taps

1. Using a label maker or tape, label each motor’s wires “A”. “B”
and “C” at the naked end
2. Mark the corresponding taps in the ESC with the same letters
a. A color code can also be used; important here is that the
taps are properly identified so they are connected to the
right cables
3. Using a label maker or tape, label the red cable on the battery side
with the corresponding motor code (“M1”, “M2”, etc.)
a. Refer to the blueprint for the position and direction of
rotation for each motor. Remember, “N” means
counterclockwise.
Step 2: Mount the foldable joints

1. Drill holes through the polycarbonate sheet on the positions


indicated in the blueprint
a. Use drills for acrylic, to avoid cracks on the surface. Use
a suitable washer if the hole is bigger than the screw’s
head.
2. Mount the foldable joints under the polycarbonate sheet; the holder
for the carbon fiber tube must be pointing outwards, perpendicular
to the lids of the sheet
a. ATTENTION: The foldable joint has a 50 angle
upwards when unfolded; make sure the joint is mounted
with the correct side up

Step 3: Mount the motors and arms

1. Attach the motor mount plate to one end of a carbon fiber tube
2. Mount the motor on the mount plate, with the wires facing the ube;
no need to tight the screws yet, since the position may be changed
after all components are in place
3. Pass the motor wires through the carbon fiber tube
4. Pass the wire through the hole at the end of the carbon fiber holder
in the foldable joint
5. Insert the other end of the carbon fiber tube in the foldable joint
holder; make sure the motor mount plate is horizontal; fasten the
tube in place
6. Adjust the motor position so its axis is 9.2” away from the
corresponding yellow ⊗ symbol marked in the blueprint and
13” from axis to axis.
7. Fasten the motor to the motor mount plate using the screws
provided by the motor manufacturer
a. ATTENTION: Be extra careful when using the screws
provided by the motor’s manufacturer; if they go too far
up they will push the motor windings and severely affect
the motor’s performance; if the screws are too long for
the mount plate use shorter M2.5 screws.

Step 4: Mount the ESCs

1. Mount the ESCs in the proper positions under the frame body per
the blueprint
a. Make sure the ESCs marked “N” are mounted to the
“CCW” positions, while the ones marked “R” are
assigned to the “CW” positions
2. Mount the PM07 power module in the proper position per the
blueprint
3. Solder the 18 AWG wires to the motor power out terminals of the
PM07
a. Use red wires for the live terminal and black wires for
ground
4. Solder the JR plug extensions to the PWM outputs of PM07
a. Solder the black wire to ground and the other wire to the
corresponding PWM output (terminal marked with M1,
M2, M3, etc.)
5. Pass the 18 AWG wires and JR plug wires through the 1” wiring
hole in the frame’s body
6. Connect the 18 AWG wires from the PM07 to the battery wires
from the ESCs, paying attention to connect each cable to the
corresponding ESC
a. Using terminal connectors instead of soldering will make
it easier to disconnect the ESCs if needed
7. Connect the JR plug extensions coming from the PM07 to the JR
plug wire from the ESC
Mounting and connecting batteries and power
As the heaviest components in the UAV, the batteries require
special care when mounted.
1. Mount the power distribution bars as indicated in the blueprint.
a. Hook and loop tape can be used but, if preferred, the
power distribution bars can be screwed in place.
2. Mount the batteries in the positions indicated in the blueprint, with
the XT90 connectors facing towards the power distribution bars
a. If using a heavy duty hook-and-loop tape/strip, make sure
it can firmly attach to plastics like polycarbonate and can
hold the battery’s weight; tapes that can hold 10 lbs or
more are recommended
b. If using a battery mount plate:
i. Make sure they are positioned in the correct
location, so the batteries are centered.
ii. Make sure they do not cover the wiring hole
iii. The blueprint does not provide hole marks for
the mount plate because different plates have
mounting holes in different positions and with
different diameters
3. Solder the 6 AWG wires to the battery terminals in the PM07 and
connect them to the power distribution bars
a. Make sure the red wire goes to the positive terminal in
the PM07 and to live power distribution bar; the black
wire goes to the ground power bar
b. It is highly recommended to use lugs clamped to the
naked end of the 6 AWG wire to make the connection to
the power distribution bar more secure.
c. Do not connect the 6 AWG wires to the main posts of the
power distribution bars, use one of the other connections
4. Connect the XT90 pigtails to the power distribution bars
a. It is highly recommended to use lug connectors clamped
to the naked end of the XT90 pigtails
b. Use the 2 main posts in the power distribution bar to
connect the XT90 pigtails
c. Connect the red wire to the live power bar and the black
wire to the ground power bar
d. IMPORTANT: Do not connect the pigtails to the
batteries until all the work is done
Mounting and connecting remaining components

1. Mount all the electronic components on the positions indicated in


the blueprint; the red arrow at the top right corner indicates the
“front” of the aircraft.
a. Pay special attention to the direction of certain
components
i. The power input for the mobile hotspot must be
facing towards the center of the aircraft
ii. The GPS/compass must be pointing to the
direction indicated by the small red arrow in
the blueprint
iii. The SBEC input wires must be facing the
power distribution blocks
iv. If using hook-and-loop fasteners to mount the
PM07 to the aircraft’s body, make sure they are
taped to the board aligned with mounting holes
2. Mount the SBEC as indicated in the blueprint and connect the input
wires to the power distribution bars
a. Make sure the jumper is in place for 5 V output
3. Using the splice terminal taps, fork the USB power cables for the
MiFi and the RPi 4 from the SPEC output cables
4. Connect the CAP & ADC IN port in the Pixhawk to the CAP &
ADC OUT port in the PM07
5. Connect the POWER 1 and POWER 2 ports in the Pixhawk to the
PWR1 and PWR2 ports in the PM07
6. Connect the I/O PWM OUT port in the Pixhawk to the IO PWM IN
port in the PM07
7. Connect the RC port in the Pixhawk to the S-BUS port in the X8R
a. This is important: The SB port in the Pixhawk is an
output port used to send S-BUS messages to servos
connected to it.
b. The signal pin in the RC port is the pin at the bottom of
the bus
8. Connect the TELEM 2 port in he PIxhawk to the Smart Port in the
X8R
9. Connect the TELEM 1 port in the Pixhawk to the RPi 4 GPIO pins
8 (TX) and 10 (RX)
a. Pin 2 from TELEM 1 (TX) in PIxhawk to pin 10 in RPi 4
(RX)
b. Pin 3 from TELEM 1 (RX) in PIxhawk to pin 8 in RPI 4
(TX)
c. Pin 6 from TELEM 1 (GND) in PIxhawk to one of the
ground pins in RPi 4 (6, 9, 14, 20, 25, 30, 34, 39)
d. PIn 1 from TELEM 1 in Pixhawk is 5V+ VCC and is
leftmost pin with the center arrow pointing up
10. Connect the GPS/compass receiver to the GPS
MODULE port in the Pixhawk
11. Mount the landing gear
Calibration and configuration

IMPORTANT: All calibration must be done without installing the


propellers.
1. Using QGroundControl, configure the parameters as described
across this book.
a. In particular, configure the following parameters:
i. PID gains (per the calculation methods
described throughout the book and assuming a
drag constant of 0.5 in the linearized ODE)
1. Altitude
a. MPC_Z_P = 0.1
2. Horizontal speed
a. MPC_XY_VEL_P = 0.15
b. MPC_XY_VEL_I = keep
default
c. MPC_XY_VEL_D = keep
default
ii. PWM_RATE to 0 (Oneshot125)
iii. PWM_MIN to 1000
iv. PWM_MAX to 1900 (this will limit the
maximum RPM to slightly less than 7000 RPM
with a 6S battery and a 330 kV motor; this will
prevent the motors from pulling too much
current)
v. MPC_XY_CRUISE set to 5 m/s
vi. SENS_BOARD_ROT set to 7
1. This value indicates the flight
controller is positioned with a 3150
yaw relative to the “front” of the
airframe.
2. Using QGroundControl, execute the Pixhawk calibration
procedure. Calibrate radio, ESCs, accelerometer, gyroscope and
compass.
3. Using QGroundControl, set up the flight modes.
Testing the configuration

1. Connect the batteries to the XT90 pigtail connectors


2. Verify all components are on
3. Verify QGroundControl can communicate with the flight controller
through the proxy server
4. Use QGroundControl to verify they are all spinning correctly
a. Make sure the correct motors start rotating when selected
b. Verify all motors are spinning in the expected direction
of rotation; if not, the ESCs must be re-programmed
accordingly
c. REMEMBER: test motors without propellers!!!
Attaching propellers and flight

1. Fasten the propeller threaded adapters to each motor


a. The adapters with clockwise threads go on the
counterclockwise rotating motors; the adapters with
counterclockwise threads go on the clockwise rotating
motors
2. Place each propeller in the corresponding adapter
3. Fasten the corresponding nuts to secure the propellers in place
4. Using the RC controller, set the flight controller into POSITION
CONTROL mode, arm and takeoff
a. IMPORTANT: only takeoff once the UAV acquired
GPS. Without GPS, it will be almost impossible to
control the UAV
5. Verify the telemetry provided by the UAV is acquired and
displayed by QGroundControl
6. If operation is successful, land the aircraft and repeat the operation
using QGroundControl
Chapter 9 - Final considerations
Objectives
This chapter covers:
● Rules and regulations for flying large UAVs
● Waivers for flying UAVs BLOS
● Limitations associated with using the mobile network for command and
control

Rules and regulations


The Federal Aviation Agency (FAA) is responsible for publishing
rules and regulations regarding operation of UAVs.
14 CFR Part 107 - SMALL UNMANNED AIRCRAFT
SYSTEMS
Part 107 [12] lists all the rules associated with flying small UAVs.
Small UAVs are those weighing less than 55 lbs on take-off.
Core rules are:
● Must fly in Visual Line of Sight (VLOS); first person view camera
cannot be used as a replacement for VLOS
● Can’t fly over people
● Daylight only operation (30 minutes before official sunrise, 50 minutes
after official sunset)
● Maximum ground speed: 100 mph
● Maximum altitude: 400 ft above ground level (AGL)
● No operation from a moving vehicle or moving aircraft
● Operator can only fly one aircraft at a time
● Operators can only fly in airspace Classes B, C, D and E with
permission from Air Traffic Control (ATC) and Class G without
permission.
● Aircraft must be inspect before flight
● Remote pilot must be certified
Remote pilot certification
Small UAV remote pilot certification can be obtained in several
airports and consists of a multiple choice test regarding flight rules and
regulations. knowledge of navigation and airspace rules.
The certification must be renewed every 2 years.
Aircraft registration
Any UAV weighing more than 0.55 lbs must be registered per 14
CFR Part 91, section 203.
Registration costs USD 5.00 and can be done online here. It is
valid for 3 years.

Waivers
Flying the aircraft outside of Part 107 requires the FAA to issue
waivers for the exception requested by the operation.
Here are some cases that require waivers:
● Operation from a moving vehicle or aircraft
● Night time operation
● Beyond visual line of sight aircraft operation
● Operation without a visual observer
● Operation of multiple small unmanned aircraft systems
● Yielding the right of way
● Operation over people
● Operation in certain airspace
● Operating limitations for small unmanned aircraft
This FAA page explains all the details regarding the process to
request a waiver.
Remote ID
As of December, 23rd, 2020, UAVs are required to fly carrying a
Remote Identification Broadcast Module, which broadcasts information
about the aircraft from take-off to shutdown.
The information broadcasted includes an aircraft unique identifier
and its location (latitude, longitude, etc.).
The broadcast is done over unlicensed radio spectrum regulated by
the Federal Communications Committee (FCC).
However, by the time this book was written, the actual
frequency/band used for the broadcast and if using the mobile cellular
network would be allowed were still under discussion.
The final rule from the FAA regarding Remote ID can be found here.

Limitations of using the mobile network


The main factor limiting usage of mobile networks in UAVs is
interference. When airborne, the UAV is in direct line of sight of base
stations that a ground user is not attached to; therefore, the radio interference
from these base stations affect both the uplink and downlink maximum data
rate that can be achieved by the UAV.
Conversely, the radio signal emitted from the UAV also appears as
interference to the base stations not serving the UAV. Consequently, the
airborne UAV also affects the ground users.
There are several on-going studies on techniques that can be used
to reduce interference effects, like Verizon’s Airborne LTE Operations
(ALO) certified modems and use of directional antennas.
Nevertheless all the issues caused by interference, the data rate
used in command, control and telemetry transmission is very small when
compared to the levels that would be impacted by radio interference.
As long as the on-board computer does not try to transmit data that
requires large bit rates (e.g., live video), operation of UAVs over mobile
cellular networks does work, even at the maximum 400 feet altitude above
ground level mandated by the FAA.
References
[1] Beléndez, A., C. Pascual, D. Méndez, T. Beléndez, and C. Neipp, 2007,
Exact solution for the nonlinear pendulum: Revista Brasileira de Ensino de
Física, v. 29, no. 4, doi:10.1590/s0102-47442007000400024.
[2] Linearization technique
[3] Center of mass
[4] Ogata K., Modern Control Engineering 5th edition Upper Saddle NJ:
Pearson Prentice Hall, 2009 ISBN 13: 978-0-13-615673-4
[5] Second Order Linear Nonhomogeneous Differential Equations; Method of
Undetermined Coefficients y″ + p(t)y′ + q(t)y = g(t),
[6] The Cubic Formula
[7] Graf, J., PID Control Fundamentals, Createspace Independent Publishing
Platform, United States, 2016 ISBN-13:978-1535358668
[8] Pixhawk | The hardware standard for open-source autopilots
[9] PX4 Firmware
[10] Microelectromechanical systems
[11] Rahul Mukherjee, Joydeep Basu, Pradip Mandal and Prasanta
Kumar Guha; A review of micromachined thermal accelerometers;
Journal of Micromechanics and Microengineering, Volume 27, Number
12
[12] 14 CFR Part 107
[13] MS5611-01BA03 Barometric Pressure Sensor, with stainless
steel cap
[14] Hall Effect
[15] Wanninger, Lambert. "Introduction to Network RTK".
www.wasoft.de. IAG Working Group 4.5.1. Retrieved 14 February
2018.
[16] Differential GNSS
[17] Inter-Integrated Circuit specification (I2C)
[18] QGC - QGroundControl - Drone Control
[19] ESC Calibration
[20] Packet Serialization
[21] Messages (common)
[22] Propeller thrust and power calculation
[24] Drone calculation spreadsheet
[25] Lipo Battery Size Chart: Dimensions, Parameters and Weight
[26] Flight Controllers
[27] Generate MAVLINK libraries
[28] PX4 Full Parameter List
[29] UART User Guide
[30] CAN bus specification - version 2.0
[31] TI KeyStone SPI User Guide
[32] PM07 Quick Start Guide
[33] APC propellers performance data
[34] Tiger Motor MN4014 kV330
[35] Blueprints - top view and bottom view
[36] WolframAlpha Online
[37] Radio calibration and configuration
[38] Flight modes configuration
[39] I2CXL-MaxSonar - EZ series
[40] LeddarOne datasheet
Appendix
A - Linearization
Linearization is based on the principle that any continuous function can be written as a series where each
factor is a higher order derivative of the original function.
Linearization only applies to regions of the function in the vicinity of the point of interest.
Here is an informal deduction of the linearization procedure. In this presentation f’(x) is used for the
first-order derivative with respect to x, f’’(x) for the second-order and so on.
From the definition of derivative, one can write:

(A.1)
valid for x in the vicinity of x0.

Equation (A.1) represents a straight line and therefore is the linearized function in the vicinity of
x0. Expanding the terms and regrouping results in the linearized function:

For example:

The range of acceptable values for x will depend on the linearization error tolerance.
For the example above:

Error tolerance (%) Acceptable range (x)


1 1.8 - 2.3
5 1.6 - 2.6
10 1.5 - 2.9
20 1.4 - 3.6

B - MAVLINK generated libraries


Here are a few examples of files and code generated for different programming languages.
C language
The C library is implemented using inline code in header files only, to optimize the use of RAM.
Folder content
-rw-rw-r-- 1 foobar foobar 2253 Sep 18 17:08 checksum.h
drwxrwxr-x 2 foobar foobar 16384 Sep 18 17:08 common
-rw-rw-r-- 1 foobar foobar 6421 Sep 18 17:08
mavlink_conversions.h
-rw-rw-r-- 1 foobar foobar 2245 Sep 18 17:08 mavlink_get_info.h
-rw-rw-r-- 1 foobar foobar 36552 Sep 18 17:08 mavlink_helpers.h
-rw-rw-r-- 1 foobar foobar 7026 Sep 18 17:08 mavlink_sha256.h
-rw-rw-r-- 1 foobar foobar 11334 Sep 18 17:08 mavlink_types.h
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:08 minimal
-rw-rw-r-- 1 foobar foobar 12255 Sep 18 17:08 protocol.h
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:08 px4

minimal/mavlink_msg_protocol_version.h

#pragma once
// MESSAGE PROTOCOL_VERSION PACKING
#define MAVLINK_MSG_ID_PROTOCOL_VERSION 300

typedef struct __mavlink_protocol_version_t {


uint16_t version; /*< Currently active MAVLink version number * 100: v1.0 is 100, v2.0 is 200, etc.*/
uint16_t min_version; /*< Minimum MAVLink version supported*/
uint16_t max_version; /*< Maximum MAVLink version supported (set to the same value as version by default)*/
uint8_t spec_version_hash[8]; /*< The first 8 bytes (not characters printed in hex!) of the git hash.*/
uint8_t library_version_hash[8]; /*< The first 8 bytes (not characters printed in hex!) of the git hash.*/
} mavlink_protocol_version_t;
#define MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN 22
#define MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN 22
#define MAVLINK_MSG_ID_300_LEN 22
#define MAVLINK_MSG_ID_300_MIN_LEN 22
#define MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC 217
#define MAVLINK_MSG_ID_300_CRC 217
#define MAVLINK_MSG_PROTOCOL_VERSION_FIELD_SPEC_VERSION_HASH_LEN 8
#define MAVLINK_MSG_PROTOCOL_VERSION_FIELD_LIBRARY_VERSION_HASH_LEN 8
#if MAVLINK_COMMAND_24BIT
#define MAVLINK_MESSAGE_INFO_PROTOCOL_VERSION { \
300, \
"PROTOCOL_VERSION", \
5, \
{ { "version", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_protocol_version_t, version) }, \
{ "min_version", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_protocol_version_t, min_version) }, \
{ "max_version", NULL, MAVLINK_TYPE_UINT16_T, 0, 4, offsetof(mavlink_protocol_version_t, max_version) }, \
{ "spec_version_hash", NULL, MAVLINK_TYPE_UINT8_T, 8, 6, offsetof(mavlink_protocol_version_t, spec_version_hash) }, \
{ "library_version_hash", NULL, MAVLINK_TYPE_UINT8_T, 8, 14, offsetof(mavlink_protocol_version_t,
library_version_hash) }, \
}\
}
#else
#define MAVLINK_MESSAGE_INFO_PROTOCOL_VERSION { \
"PROTOCOL_VERSION", \
5, \
{ { "version", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_protocol_version_t, version) }, \
{ "min_version", NULL, MAVLINK_TYPE_UINT16_T, 0, 2, offsetof(mavlink_protocol_version_t, min_version) }, \
{ "max_version", NULL, MAVLINK_TYPE_UINT16_T, 0, 4, offsetof(mavlink_protocol_version_t, max_version) }, \
{ "spec_version_hash", NULL, MAVLINK_TYPE_UINT8_T, 8, 6, offsetof(mavlink_protocol_version_t, spec_version_hash) }, \
{ "library_version_hash", NULL, MAVLINK_TYPE_UINT8_T, 8, 14, offsetof(mavlink_protocol_version_t,
library_version_hash) }, \
}\
}
#endif
/**
* @brief Pack a protocol_version message
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
*
* @param version Currently active MAVLink version number * 100: v1.0 is 100, v2.0 is 200, etc.
* @param min_version Minimum MAVLink version supported
* @param max_version Maximum MAVLink version supported (set to the same value as version by default)
* @param spec_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
* @param library_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_protocol_version_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
uint16_t version, uint16_t min_version, uint16_t max_version, const uint8_t *spec_version_hash, const uint8_t
*library_version_hash)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN];
_mav_put_uint16_t(buf, 0, version);
_mav_put_uint16_t(buf, 2, min_version);
_mav_put_uint16_t(buf, 4, max_version);
_mav_put_uint8_t_array(buf, 6, spec_version_hash, 8);
_mav_put_uint8_t_array(buf, 14, library_version_hash, 8);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN);
#else
mavlink_protocol_version_t packet;
packet.version = version;
packet.min_version = min_version;
packet.max_version = max_version;
mav_array_memcpy(packet.spec_version_hash, spec_version_hash, sizeof(uint8_t)*8);
mav_array_memcpy(packet.library_version_hash, library_version_hash, sizeof(uint8_t)*8);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_PROTOCOL_VERSION;
return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
}
/**
* @brief Pack a protocol_version message on a channel
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param version Currently active MAVLink version number * 100: v1.0 is 100, v2.0 is 200, etc.
* @param min_version Minimum MAVLink version supported
* @param max_version Maximum MAVLink version supported (set to the same value as version by default)
* @param spec_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
* @param library_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
* @return length of the message in bytes (excluding serial stream start sign)
*/
static inline uint16_t mavlink_msg_protocol_version_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg,
uint16_t version,uint16_t min_version,uint16_t max_version,const uint8_t *spec_version_hash,const uint8_t
*library_version_hash)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN];
_mav_put_uint16_t(buf, 0, version);
_mav_put_uint16_t(buf, 2, min_version);
_mav_put_uint16_t(buf, 4, max_version);
_mav_put_uint8_t_array(buf, 6, spec_version_hash, 8);
_mav_put_uint8_t_array(buf, 14, library_version_hash, 8);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN);
#else
mavlink_protocol_version_t packet;
packet.version = version;
packet.min_version = min_version;
packet.max_version = max_version;
mav_array_memcpy(packet.spec_version_hash, spec_version_hash, sizeof(uint8_t)*8);
mav_array_memcpy(packet.library_version_hash, library_version_hash, sizeof(uint8_t)*8);
memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN);
#endif
msg->msgid = MAVLINK_MSG_ID_PROTOCOL_VERSION;
return mavlink_finalize_message_chan(msg, system_id, component_id, chan,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
}
/**
* @brief Encode a protocol_version struct
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param msg The MAVLink message to compress the data into
* @param protocol_version C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_protocol_version_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const
mavlink_protocol_version_t* protocol_version)
{
return mavlink_msg_protocol_version_pack(system_id, component_id, msg, protocol_version->version, protocol_version-
>min_version, protocol_version->max_version, protocol_version->spec_version_hash, protocol_version->library_version_hash);
}
/**
* @brief Encode a protocol_version struct on a channel
*
* @param system_id ID of this system
* @param component_id ID of this component (e.g. 200 for IMU)
* @param chan The MAVLink channel this message will be sent over
* @param msg The MAVLink message to compress the data into
* @param protocol_version C-struct to read the message contents from
*/
static inline uint16_t mavlink_msg_protocol_version_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan,
mavlink_message_t* msg, const mavlink_protocol_version_t* protocol_version)
{
return mavlink_msg_protocol_version_pack_chan(system_id, component_id, chan, msg, protocol_version->version, protocol_version-
>min_version, protocol_version->max_version, protocol_version->spec_version_hash, protocol_version->library_version_hash);
}
/**
* @brief Send a protocol_version message
* @param chan MAVLink channel to send the message
*
* @param version Currently active MAVLink version number * 100: v1.0 is 100, v2.0 is 200, etc.
* @param min_version Minimum MAVLink version supported
* @param max_version Maximum MAVLink version supported (set to the same value as version by default)
* @param spec_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
* @param library_version_hash The first 8 bytes (not characters printed in hex!) of the git hash.
*/
#ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS
static inline void mavlink_msg_protocol_version_send(mavlink_channel_t chan, uint16_t version, uint16_t min_version, uint16_t
max_version, const uint8_t *spec_version_hash, const uint8_t *library_version_hash)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char buf[MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN];
_mav_put_uint16_t(buf, 0, version);
_mav_put_uint16_t(buf, 2, min_version);
_mav_put_uint16_t(buf, 4, max_version);
_mav_put_uint8_t_array(buf, 6, spec_version_hash, 8);
_mav_put_uint8_t_array(buf, 14, library_version_hash, 8);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PROTOCOL_VERSION, buf,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
#else
mavlink_protocol_version_t packet;
packet.version = version;
packet.min_version = min_version;
packet.max_version = max_version;
mav_array_memcpy(packet.spec_version_hash, spec_version_hash, sizeof(uint8_t)*8);
mav_array_memcpy(packet.library_version_hash, library_version_hash, sizeof(uint8_t)*8);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PROTOCOL_VERSION, (const char *)&packet,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
#endif
}
/**
* @brief Send a protocol_version message
* @param chan MAVLink channel to send the message
* @param struct The MAVLink struct to serialize
*/
static inline void mavlink_msg_protocol_version_send_struct(mavlink_channel_t chan, const mavlink_protocol_version_t*
protocol_version)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
mavlink_msg_protocol_version_send(chan, protocol_version->version, protocol_version->min_version, protocol_version-
>max_version, protocol_version->spec_version_hash, protocol_version->library_version_hash);
#else
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PROTOCOL_VERSION, (const char *)protocol_version,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
#endif
}
#if MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN <= MAVLINK_MAX_PAYLOAD_LEN
/*
This variant of _send() can be used to save stack space by re-using
memory from the receive buffer. The caller provides a
mavlink_message_t which is the size of a full mavlink message. This
is usually the receive buffer for the channel, and allows a reply to an
incoming message with minimum stack space usage.
*/
static inline void mavlink_msg_protocol_version_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, uint16_t version,
uint16_t min_version, uint16_t max_version, const uint8_t *spec_version_hash, const uint8_t *library_version_hash)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
char *buf = (char *)msgbuf;
_mav_put_uint16_t(buf, 0, version);
_mav_put_uint16_t(buf, 2, min_version);
_mav_put_uint16_t(buf, 4, max_version);
_mav_put_uint8_t_array(buf, 6, spec_version_hash, 8);
_mav_put_uint8_t_array(buf, 14, library_version_hash, 8);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PROTOCOL_VERSION, buf,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
#else
mavlink_protocol_version_t *packet = (mavlink_protocol_version_t *)msgbuf;
packet->version = version;
packet->min_version = min_version;
packet->max_version = max_version;
mav_array_memcpy(packet->spec_version_hash, spec_version_hash, sizeof(uint8_t)*8);
mav_array_memcpy(packet->library_version_hash, library_version_hash, sizeof(uint8_t)*8);
_mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PROTOCOL_VERSION, (const char *)packet,
MAVLINK_MSG_ID_PROTOCOL_VERSION_MIN_LEN, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN,
MAVLINK_MSG_ID_PROTOCOL_VERSION_CRC);
#endif
}
#endif
#endif
// MESSAGE PROTOCOL_VERSION UNPACKING

/**
* @brief Get field version from protocol_version message
*
* @return Currently active MAVLink version number * 100: v1.0 is 100, v2.0 is 200, etc.
*/
static inline uint16_t mavlink_msg_protocol_version_get_version(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 0);
}
/**
* @brief Get field min_version from protocol_version message
*
* @return Minimum MAVLink version supported
*/
static inline uint16_t mavlink_msg_protocol_version_get_min_version(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 2);
}
/**
* @brief Get field max_version from protocol_version message
*
* @return Maximum MAVLink version supported (set to the same value as version by default)
*/
static inline uint16_t mavlink_msg_protocol_version_get_max_version(const mavlink_message_t* msg)
{
return _MAV_RETURN_uint16_t(msg, 4);
}
/**
* @brief Get field spec_version_hash from protocol_version message
*
* @return The first 8 bytes (not characters printed in hex!) of the git hash.
*/
static inline uint16_t mavlink_msg_protocol_version_get_spec_version_hash(const mavlink_message_t* msg, uint8_t
*spec_version_hash)
{
return _MAV_RETURN_uint8_t_array(msg, spec_version_hash, 8, 6);
}
/**
* @brief Get field library_version_hash from protocol_version message
*
* @return The first 8 bytes (not characters printed in hex!) of the git hash.
*/
static inline uint16_t mavlink_msg_protocol_version_get_library_version_hash(const mavlink_message_t* msg, uint8_t
*library_version_hash)
{
return _MAV_RETURN_uint8_t_array(msg, library_version_hash, 8, 14);
}
/**
* @brief Decode a protocol_version message into a struct
*
* @param msg The message to decode
* @param protocol_version C-struct to decode the message contents into
*/
static inline void mavlink_msg_protocol_version_decode(const mavlink_message_t* msg, mavlink_protocol_version_t* protocol_version)
{
#if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS
protocol_version->version = mavlink_msg_protocol_version_get_version(msg);
protocol_version->min_version = mavlink_msg_protocol_version_get_min_version(msg);
protocol_version->max_version = mavlink_msg_protocol_version_get_max_version(msg);
mavlink_msg_protocol_version_get_spec_version_hash(msg, protocol_version->spec_version_hash);
mavlink_msg_protocol_version_get_library_version_hash(msg, protocol_version->library_version_hash);
#else
uint8_t len = msg->len < MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN? msg->len :
MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN;
memset(protocol_version, 0, MAVLINK_MSG_ID_PROTOCOL_VERSION_LEN);
memcpy(protocol_version, _MAV_PAYLOAD(msg), len);
#endif
}

Java
Folder content

drwxrwxr-x 7 foobar foobar 4096 Sep 18 17:25 .


drwxrwxr-x 12 foobar foobar 4096 Sep 18 10:23 ..
drwxrwxr-x 2 foobar foobar 12288 Sep 18 17:25 common
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:25 enums
-rw-rw-r-- 1 foobar foobar 36903 Sep 18 17:25
MAVLinkPacket.java
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:25 Messages
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:25 minimal
-rw-rw-r-- 1 foobar foobar 3965 Sep 18 17:25 Parser.java
drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:25 px4

Messages

drwxrwxr-x 2 foobar foobar 4096 Sep 18 17:25 .


drwxrwxr-x 7 foobar foobar 4096 Sep 18 17:25 ..
-rw-rw-r-- 1 foobar foobar 823 Sep 18 17:25
MAVLinkMessage.java
-rw-rw-r-- 1 foobar foobar 5905 Sep 18 17:25
MAVLinkPayload.java
-rw-rw-r-- 1 foobar foobar 4625 Sep 18 17:25 MAVLinkStats.java

Each message extends MAVLinkMessage.java

/* AUTO-GENERATED FILE. DO NOT MODIFY.


*
* This class was automatically generated by the
* java mavlink generator tool. It should not be modified by hand.
*/
package com.MAVLink.Messages;
import java.io.Serializable;
import com.MAVLink.MAVLinkPacket;
public abstract class MAVLinkMessage implements Serializable {
private static final long serialVersionUID = -7754622750478538539L;
// The MAVLink message classes have been changed to implement Serializable,
// this way is possible to pass a mavlink message through the Service-Acctivity
interface

/**
* Simply a common interface for all MAVLink Messages
*/

public int sysid;


public int compid;
public int msgid;
public abstract MAVLinkPacket pack();
public abstract void unpack(MAVLinkPayload payload);
}

Class Messages/MAVLinkPayload.java takes care of encoding/decoding the data.


common

Folder with the implementation of the encoding and decoding of each MAVLINK message.
C - Radio controller setup (PX4/Pixhawk 4)
The Pixhawk 4 provides multiple interfaces - Smart-Bus (S-BUS),
PPM and DSM - for connecting radio controller receivers.
This section describes how to use the S-BUS interface.

Smart-Bus protocol (S-BUS)


The S-BUS protocol, originally created by Futaba, is a serial
protocol derived from RS232 but using inverted signals for “0” and “1”. It
uses 8 bits, 1 parity bit, 2 stop bits (8E2).
The protocol sends 25 bytes every 14 ms. The 25 bytes are
encoded as follows:

The value in each channel maps to the appropriate width of the


output PWM pulse injected in the corresponding ESC. A copter with 8
propellers only uses the main 8 PWM outputs.

S-BUS cable
Use an S-BUS cable to connect the Pixhawk 4 to a S-BUS capable
receiver, like the FrSky X8R.
Telemetry data (optional)
If using the FrSky X8R receiver with the Taranis X9D transmitter, it
is possible to connect one of the telemetry ports in the Pixhawk 4 to the X8R
receiver so the transmitter can display useful telemetry information from the
flight controller.
In order to do so, connect the TELEM 2 port to the Smart Port in the
X8R using the appropriate specialized cable or adapter, like the FrSky Yaapu
Telemetry Converter Cable.

D - GroundControl communication link setup


1. On the laptop connected to the Internet, open QGroundControl and
click on the “Q” on the top left corner

2. Select Application Settings option in the menu on the left


3. Select the Comm links option in the menu on the left

4. Select Add from the menu at the bottom


5. Provide a name for the connection, select TCP from the menu,
populate the IP address and port number 54321 for the server
application; then press OK at the right bottom corner.
If everything is properly configured QGroundControl will start
communicating with the on-board computer in the UAV through the server.
It will pull the parameters from the UAV and will start displaying
telemetry.

E - Propeller thrust and power calculation -


momentum method
The approximate formulae for the thrust generated by a rotating
propeller and the power required to produce that thrust are derived from
general definitions of momentum, force and power.
A propeller with one blade can be approximately modeled as a
disk with area A with air flowing through the rotating propeller:
The mass of the air within the cylinder is:

(D.1)
where:
⍴ = density of air
V = volume of the cylinder
A = effective area of the propeller
Therefore,

(D.2)
where:
vp = velocity of air flowing through the propeller

From the laws of mechanics, force is the time derivative of the


linear momentum delta:

(D.3)
where:
ve = escape velocity of the mass of air, considered constant for the
calculation
vi = intake velocity of the mass air at the propeller, considered constant for
the calculation
This is known as the thrust equation..
Replacing (D.2) in (D.3), results:

(D.4)
On the other hand, Bernoulli’s equation relates pressure over a
surface to the fluid speed.
The pressure differential between the 2 surfaces of the disk
representing the propeller, assuming the static pressure is the same on both
sides, is the difference between the dynamic pressure on each side of the
disk:
(D.5)

Force is pressure x area, so the thrust generated by the propeller can


be written as:

(D.6)
Equating (D.4) and (D.6), the value for vp can be calculated:

(D.7)
Replacing (D.7) in (D.4) and assuming vi = 0 (the UAV is hovering
in place):

(D.8)
Replacing (D.7) in (D.2):

(D.9)
The propeller’s pitch is the distance traveled by the propeller in
one full rotation. Therefore:
(D.10)
where:
Rs = rotations per second
p = pitch (m)
Replacing (D.10) in (D.8) and the area by the area of the circle
results:

(D.11)
where:
D = diameter of the propeller
The power associated with moving the air mass at a speed ve is:

(D.12)
Replacing (D.8I) in (D.12):

(D.13)
Combing (D.13) and (D.8) and resolving for ve, the expression relating thrust
and power is:

(D.14)

Replacing the area with the the area of the circle in (D.14) results:

(D.15)
Again, these equations are ideal and many physical effects are left
out. They are useful as a means to provide a ballpark for the actual values.
Once in possession of the numbers generated by these equations,
the designer must rely on power and thrust tables provided by the propeller
and motor manufacturers to refine the calculations.
F - Raspberry Pi 4 serial port configuration
The Raspberry Pi comes with a 40-pin General Purpose I/O - GPIO - and each pin can be
configured with different functions. In fact, it comes out of the box with a number of pins pre-configured
with different interfaces.

Pin address
The diagram below shows the pin-out configuration of the GPIO bus, indicating the physical
position of each pin and its address.

Figure 27: Raspberry Pi 4 GPIO pinout


(Source: https://www.raspberrypi.org/documentation/usage/gpio/images/GPIO-Pinout-Diagram-2.png
Credit: Raspberry Pi Foundation, License: CC BY-SA, via Wikimedia Commons)

Configuring the primary UART for use with Pixhawk


The primary UART in the Raspberry Pi 4 is configured to pins 8 (GPIO 14) and 10 (GPIO
15). By default, the console interface is mapped to these pins.
In order to disable the console on this interface, follow this procedure:
1. Connect the RPi 4 to a monitor and keyboard
2. Open a terminal window
3. Run sudo raspi-config
4. In the dialog that will be displayed, use the keyboard keys to:
a. Scroll to and select Interface Options
b. Scroll to and select Serial
c. When prompted if a login shell should be accessible over serial, select ‘No’
d. When prompted if the serial port hardware should be enabled select ‘Yes’
5. Exit and reboot to persist the configuration
The device mapped to this serial port is /dev/ttyS0
Configuring a secondary serial port
Raspberry Pi 4 provides 6 UARTs that can be enabled and used as serial ports; that’s a real
improvement compared to previous versions, which offered only 2 ports.
UART 0 is already in use, per previous section.
UART 1 normally has other uses’ like connection to the LAN/Bluetooth controller.
UARTs 2 to 5 are, theoretically, free to be used.
These UARTs are physically mapped to the following GPIO/pins:

TX RX
UART
PIN GPIO PIN GPIO
2 27 0 28 1
3 7 4 29 5
4 24 8 21 9
5 32 12 33 13

By looking at the RPi 4 pinout, it’s clear that some of these pins are allocated for other
functionality by default:
PINs 27 - 28: allocated to EEPROM ID
PINs 21 - 24: SPI functionality (MISO and clock)
PIN 7: General purpose clock
PINs 32-33: PWM 0 and 1
From this list of functions, the one unlikely to be used in the UAV is the PWM signal, so
UART5 is recommended if a secondary serial port is needed (e.g., for communication with the RTK
component).
Configuring the UART is relatively easy.
1. Connect the RPi 4 to a monitor and keyboard
2. Open a terminal window
3. Open file /boot/config.txt using a text editor (e.g. Vim)
a. Caution: the editor must be executed with root privileges, for example, using the
sudo command (e.g. sudo vim /boot/config.txt)
4. Go to the end of the file and add this line: dtoverlay = uart5
5. Save the modification and reboot

The device mapped to the secondary serial port is /dev/ttyAMA1.

G - Launching an app on startup on RPi 4


Here it is described how to set up the RPi 4 to run the proxy client responsible for sending
telemetry from the Pixhawk to the server and sending commands from the server to the Pixhawk.
The method described here is the simplest in Linux-based systems.
1. Open file /etc/rc.local

sudo nano
/etc/rc.local

2. Go to the end of the file, just before line exit 0


3. Add the following line:

java -jar <path/to/proxy_client/JAR/file> -i obc -h <IP address or URL for the AWS
server>

4. Save the file and reboot the RPi 4

Once the RPi 4 is connected to the network, the client will automatically start interacting with
the server and the PIxhawk.
The server will display logs on the terminal indicating when connection to the OBC is
successfully completed.

You might also like