Program a Raspberry Pi Drone

in #technology7 years ago

Here we go

pxfmini-mounted-on-drone.jpg

The Raspberry Pi is a fantastic project board. Since we love a challenge, we set out looking for something that would really push the limits of our hacking and coding skills. We chose a Raspberry Pi Drone. Kits for drones, or quadcopters, are available as ready-tofly (RTF) if you just want the joy of flight, but where’s the challenge in that?

We started with an almost-ready-to-fly (ARF) kit – the DJI Flame Wheel F450 – all the hardware, but none of the control electronics or software. Many enthusiasts have created DIY drones using Arduino microcontrollers, so we knew a DIY build was possible, but very few, if any, have successfully used the Raspberry Pi.

This article uses Python code as a guide to what’s needed to build a drone. You can download the full code from www.linuxuser. co.uk/raspicode. We’ll be metaphorically bolting it together so that by the end of this guide you don’t just understand the code but also the interaction with the real-world, all in order to enable you to build your own drone with confidence.

1.png

Understanding Drones...

Although this article focuses on software, a very basic background in the hardware from the kit is necessary to provide context. A quadcopter-type drone, which we’re building here, has four propellers pointing upwards to the sky (hence the name), each attached to its own brushless DC motor at one of the four corners of (usually) a square frame. Two motors spin clockwise, two anticlockwise, to minimise angular momentum of the drone in flight.

Each motor is driven independently by an electronic speed controller (ESC). The motors themselves have three sets of coils (phases), and the ESCs convert a pulsewidth-modulation (PWM) control signal from software/ hardware to the three phase high-current output to drive the motors at a speed determined by the control signal. The power for the ESCs and everything else on the system comes from a Lithium Polymer battery (LiPo) rated at 12V, 3300mA with peak surge current of 100A – herein lies the power!

3.png

Above How sensors in the drone point of view are converted to the Earth (horizontal/vertical) viewpoint to provide horizontal motion

Interpreter

The command interpreter converts a series of commands either from a radio control or programmed into the code itself. The commands combine the direction and speed compared to the horizon that the user want the drone to follow. The code converts these commands into a series of targets for vertical speed, horizontal speed and yaw speed – any command from a pair of joysticks can be broken down into a set of these targets.

Inputs

The inputs to the drone come from a series of electronic sensors providing information about its movement in the air. The main two are an accelerometer which measures acceleration force (including gravity) in the three axes of the drone, and a gyroscope which measures the angular speed with which the drone is pitching (nose/tail up and down), rolling (left/right side up and down), and yawing (spinning clockwise and anticlockwise around the central axis of the drone itself).

Axes

The accelerometer is relative to the orientation of drone axes, but the command targets are relative to the Earth’s axes – the horizon and gravity. To convert the sensor output between the drone axes and the Earth axes needs a little trigonometry and knowledge of the tilt angles in pitch and roll axes of the drone with respect to the Earth.

Angles

Both the accelerometer and gyro can provide this angle information, but both have flaws.

The accelerometer output can be used to calculate the angle by using the Euler algorithm. However, the accelerometer output is plagued by noise from the motors/propellers, meaning a single reading can be hugely inaccurate; on the plus side, the average reading remains accurate over time.

In contrast, the gyro output does not suffer from the noise, but since it is the angular speed being measured, it needs to be integrated over time to find the absolute angle of the drone in comparison to the horizon. Rounding errors in the integration lead to ever increasing errors over time, ultimately curtailing the maximum length of a flight.

4.png

**Filter **

Although independently they are both flawed, they can be merged mathematically such that each compensates for the flaws in the other, resulting in a noise-free, longterm accurate reading. There are many versions of these mathematical noise/drift filters. The best common one is by Kalman; the one we’ve chosen is slightly less accurate, but easier to understand and therefore to code: the complementary filter.

Now with an accurate angle in hand, it’s possible to convert accelerometer sensor data to inputs relative to the Earth’s axes and work out how fast the drone is moving up, down, left, right and forwards and backwards compared to the targets that have been set.

**PIDs **

So we now have a target for what we want the drone to do, and an input for what it’s doing, and some motors to close the gap between the two; all we need now is a way to join these together. A direct mathematical algorithm is nigh on impossible – accurate weight of the drone, power per rotation of each blade, weight imbalance etc would need to be incorporated into the equation. And yet none of these factors is stable: during flights (and crashes!), blades get damaged, batteries move in the frame, grass/mud/ moisture changes the weight of the drone, humidity and altitude would need to accounted for. Hopefully it’s clear this approach simply won’t fly.

Instead, an estimation method is used with feedback from the sensors to fine-tune that estimate. Because the estimation/feedback code loop spins at over 100 times a second, this approach can react to ‘errors’ very quickly indeed, and yet it knows nothing about all the factors which it is compensating for – that’s all handled blindly by the feedback; this is the PID algorithm.

5.png

It takes the target, subtracts the feedback input, resulting in the error. The error is then processed via a Proportional, Integral and a Differential algorithm to produce the output.

Blender

The outputs are applied to each ESC in turn: the vertical speed output is applied equally to all blades; the pitch rate output is split 50/50 subtracting from the front blades and adding to the back, producing the pitch. Roll is handled similarly. Yaw too is handled in a similar way, but applied to diagonal blades which spin in the same direction.

These ESC-specific outputs are then converted to a PWM signal to feed to the hardware ESCs with the updated propeller/motor speeds.

Code and reality

In this code, there are nine PIDs in total. In the horizontal plane, for both the X and Y axes, the horizontal speed PID converts the user-defined desired speed to required horizontal acceleration/ angle of tilt; the angles PID then converts this desired tilt angle to desired tilt rate which the rotation speed PID converts to changes in motors speeds fed to the front/back or left/right motors for pitch/ roll respectively.

In the vertical direction, a single PID converts the desired rate of ascent/descent to the acceleration output applied to each plate equally.

Finally, prevention of yaw (like a spinning top) uses two PIDs – one to set the desired angle of yaw, set to 0, and one to set the yaw rotation speed. The output of these is fed to the diagonally opposing motors which spin in the same direction.

The most critical of the nine are pitch/roll/yaw stability. These ensure that whatever other requirements enforced by other PIDs and external factors, the drone is stable in achieving those other targets; without this stability, the rest of the PIDs cannot work. Pitch is controlled by relative speed differences between the front and back propellers; roll by left and right differences, and yaw by clockwise/ anticlockwise differences from the corresponding PIDs’ outputs. The net outputs of all three PIDs are then applied to the appropriate combination of motors’ PWM channels to set the individual pulse widths.

With stability assured, some level of take-off, hover and landing can be achieved using the vertical speed PID. Placing the drone on a horizontal surface, set the target to 0.5 m/s and off she zooms into the air, while the stability PID ensures that the horizontal attitude on take-off is maintained throughout the short flight, hover and landing.

6.png

Above The orientation of the drone compared to the direction of travel, the rotation of the propellers and the axes used in the code

Up to this stage, the PIDs are independent. But what about for horizontal movement target, and suppression of drifting in the wind?

Taking the drift suppression first, a drone in a headwind will drift backwards due to the force applied by the wind. To compensate, it must tilt nose down at some angle so that some of the propellers’ thrust is applied horizontally to counteract the wind. In doing so, some of the power keeping the drone hovering at a fixed height is now battling the wind; unless the overall power is increased, the drone will start descending.

Horizontal movement is more complex still. The target is to move forwards at say one metre per second. Initially the requirement is similar to the headwind compensation - nose down plus increased power will apply a forward force leading to forward acceleration. But once that horizontal speed is attained, the drone needs to level off to stop the acceleration, but at the same time, friction in the air will slow the movement. So there’s a dynamic tilting fore/aft to maintain this stable forward velocity.

Both wind-drift suppression and controlled horizontal movement use nested PIDs; the X and Y axes horizontal speed PIDs’ outputs are used as the pitch and roll angle PIDs targets; their output feeds the pitch and roll rate PIDs to ensure stability while meeting those angular targets. The sensor feedback ensures that as the desired horizontal speed is approached, the horizontal speed PID errors shrink, reducing the targets for the angular pitch PID, thus bringing the drone’s nose back up to horizontal again.

Hopefully it now becomes clearer why accurate angle tracking is critical: in the nose-down, headwind example, the input to the vertical speed PID from the sensors is reduced by the cosine of the measured angle of ’copter tilt with respect to the horizon.

Similarly, X and Y axis speed PID sensor inputs need compensating by pitch and roll angles when comparing target speeds against accelerometer readings.

“The X and Y axes horizontal speed PIDs’ outputs are used as the pitch and roll angle PIDs targets”

“For pitch tuning, disable two diagonally opposed motors and rest these on a surface – the drone sits horizontal in between”

Experimentation and tuning

While the code accurately reflects everything we’ve described here, there’s one critical set of steps which can only be found through live testing; these are the PID gains. For each PID running, there is an independent Proportional, Integral and Differential gain that can only be found with estimation/ experimentation. The results for every drone will be different. Luckily there is a relatively safe way to proceed.

First, find the PWM take-off speed: this is done by sitting your drone on the ground and slowly increasing the PWM value until she starts looking light-footed – for your expert, this was about the 1590us pulse width (or 1000us + 590us, as shown in the code).

Next, sorting out the stability PIDs – assuming your drone is square and its balance is roughly central, then the result of pitch tuning also applies to yaw tuning. For pitch tuning, disable two diagonally opposed motors and rest these on a surface – the drone sits horizontal in between. Power up the dangling motors’ PWM to just under take-off speed (1550us pulse width in our expert’s case). Does the drone rock manically, wobble in some pretence of control, self-right when nudged, or do nothing? Tweak the P gain accordingly. Once P gain is good, add a touch of I gain – this will ensure return to 0 as well as stability. D gain is optional, but adds firmness and crisp response. Tapping a D-gain stable drone is like knocking on a table – it doesn’t move.

Vertical speed PID can be guesstimated. 1590us is taking off; desired take-off speed is 0.5m/s so a P gain of 100 is okay. No I or D gain needed.

With that a real take-off, hover and landing are safe, which is good as these are the only way to tune the directional PIDs. Just be cautious here – excessive gains lead to drones slamming into walls or performing somersaults in mid-air before powering themselves into the ground. Best executed outside in a large open field/ garden/park where the ground is soft after overnight rain!

There isn’t a shortcut to this, so just accept there will be crashes and damage and enjoy the carnage as best you can!

Assuming all the above has gone to plan, then you have a drone that takes off, hovers and lands even in breezy conditions. Next step is to add a remote control, but that’s for another issue of RasPi…

“Excessive gains lead to drones slamming into walls or performing somersaults in mid-air before powering themselves into the ground”

Sort:  

This is plagiarised yet again/ https://archive.org/stream/RasPi_Issue_1_2015_UK/RasPi_Issue_1_2015_UK_djvu.txt

It is from a magazine? I think. This is just blatantly copied, no point in upvoting him. State the source please

Whats the problem with you people, why can't you let me survive and earn a little.

I am sharing this content here so what is the fucking problem with you people.

You are not sharing it, you are copying it and claiming it as your own as you have not mentioned the source.

Also, Fuck you!

Your puny attempts trying to flag me won't work. Good luck :)

Interesting post..good work friend .upvote.greets

Great post my brother

Fllow + 100% upvote to u

Plz see my page and upvote

keep on resteeming,

Nice drone friend...it would be nice to have that here in Marawi clash...

Coin Marketplace

STEEM 0.20
TRX 0.14
JST 0.029
BTC 67900.86
ETH 3250.85
USDT 1.00
SBD 2.63