CleanFlight PID Tuning

“Tune your PID’s man”

Your Host: John Case (Casey101 on RCGroups)

This class came about from trying to find information about PID tuning my new ZMR250 Quad that I built. I sought out information about how to make my ZMR250 fly like my NanoQx. All the responses that I got were to tune my PID settings. I went looking for information about how to do just that. It seems the information for PID tuning is kind of like the black arts, bits and pieces spread all over the place.

As I posted looking for information and searched the web. The response was always; “tune your PID’s man”. But what does that mean? How do you do it? What the hell is a PID? Can someone give me PID their PIDS? Help me please?

Those are all valid questions and ones I saw repeatedly while searching for the elusive PID, reminds me of going ‘snipe hunting’.

Gathering up sources and asking for permission to use various information around the web I’m going to try to explain how to “tune your PID man”

A little background is in order so we can have a common reference:

The multirotor that I’m using is a ZMR250 clone as described by RC Model Reviews in his video series Low-cost mini-quadcopter build. The actual MultiRotor does not matter when tuning your PID’s, the procedure is the same.

The ZMR is built around the AfroFlight Naze32 Acro AbuseMark FunFly Controller running CleanFlight The rest of your build does not really matter for this class. The PID tuning results are unique to each multirotor.

While this course is centered around the Naze32 Acro running CleanFlight. The principals of tuning will apply to various Flight Controllers running other hardware/software       combinations. CleanFlight has it roots in MultiWii, therefore much of the information    that pertains to MultiWii also pertains to CleanFlight as it shares much of the same basecode.

RCGroup thread regarding this class

Mini quad PID tuning from start to finish

I’ll try to address some of the questions asked above:

What the hell is a PID?

proportional-integral-derivative controller (PID controller) is a control loop feedback mechanism (controller) widely used in industrial control systems. A PID controller calculates an error value as the difference between a measured process variable and a desired setpoint. What the above actually means is that when you move your controller stick, the quad responds, the “PID” checks to see if your quad moved to the desired setpoint of your stick movement. This is interpreted as an error, in which the PID controller attempts to correct and move the craft to the desired position indicated by the sticks. If it did not then it tries to correct that error and establish the correct orientation that you instructed by moving the controller stick. In Angle (self level mode) the PID controls the motors to establish a level stable multirotor.

What are PID’s?

The PID controller algorithm involves three separate constant parameters, and is accordingly sometimes called three-term control: the proportional, the integral and derivative values

The P term; the proportional controls the strength of the correction that is applied to bring the craft toward the target angle or rotation rate. If the P term is too low, the craft will be difficult to control as it won’t respond quickly enough to keep itself stable. If it is set too high, the craft will rapidly oscillate/shake as it continually overshoots its target.

The I term; the integral corrects small, long term errors. If it is set too low, the craft’s attitude will slowly drift. If it is set too high, the craft may oscillate (but with slower oscillations than with P being set too high).

The D term; the derivative attempts to increase system stability by monitoring the rate of change in the error. When the P term is changing rapidly, the D term causes the strength of the correction to be backed off. When the P term is stable, the D term is low, allowing the output of the PID controller to move more freely

Understanding impact of P, I and D

P – proportional

P provides a proportional amount of corrective force based upon the angle of error from desired position. The larger the deviation, the larger the corrective force.

A higher P value will create a stronger force to return to desired position.
If the P value is too high, on the return to initial position, it will overshoot and then opposite force is needed to compensate. This creates an oscillating effect until stability is eventually reached or in severe cases, the overshoot becomes amplified and the multirotor becomes completely destabilised.

Increasing value for P:
It will become more solid/stable until P is too high where it starts to oscillate and loose control. You will notice a very strong resistive force to any attempts to move the MultiRotor

Decreasing value for P:
It will start to drift in control until P is too low when it becomes very unstable.
Will be less resistive to any attempts to change orientation

Aerobatic flight: Requires a slightly higher P
Gentle smooth flight: requires a slightly lower lower P

I – Integral

I provides a variable amount of corrective force based upon the angle of error from desired position. The larger the deviation and / or the longer the deviation exists, the larger the corrective force. It is limited to prevent becoming excessively high.

A higher I will increase the heading hold capability

Increasing value for I:
Increase the ability to hold overall position, reduce drift due to unbalanced frames etc

Decreasing value for I:
Will improve reaction to changes, but increase drift and reduce ability to hold position

Aerobatic flight:
Gentle smooth flight:
AP: Requires a slightly lower I to minimize wobbles / jitters

D – Derivative

This moderates the speed at which the MultiRotor is returned to its original position.
A lower D will mean the MultiRotor will snap back to its initial position very quickly

Increasing value for D:
Dampens changes. Slower to react to fast changes

Decreasing value for D:
Less dampening to changes. Reacts faster to changes

Aerobatic flight: Lower D
Gentle smooth flight: Increase D

What does it mean to tune your PID?

The “PIDs” are a set of tuning parameters which control the operation of the PID controller. The optimal PID settings to use are different on every craft, so if you can’t find someone with your exact setup who will share their settings with you, some trial and error is required to find the best performing PID settings. Excellent reference provided by joshuabardwell regarding PID tuning

The basic PIDs apply to all modes, but there are additional adjustments for angle and horizon. You have to get the basic PIDs working in acro (rate mode) before you try to tune any of the self-leveling settings, or you'll never be able to get them right. Seebelow for information about calibrating a stable hover in autolevel modes.

Here is a video further explaining Multicopter Tuning – Introduction to PID theory and how to tune your multirotor provided by Painless360

Can someone give me their PID settings?

Yes and no.

PID settings can be shared with great success, only if you have the exact same multirotor and power system. If not it may get you close but further tuning will be required. The reason for the differences between PID settings of one multirotor to another includes but is not limited to the following:

  • Center of Gravity
  • Motors (size, responsiveness, propellers, balance, angle of the motors)
  • ESC’s
  • Frame design & layout(symmetrical, “H” configuration, etc.
  • Personal preference (racing, acrobatics, FPV, using Acro/Angle/Horzion mode
  • Your flying ability

Here is a link to a thread on RCGroups.com with people attempting to share their PID settings.

How do I tell a good PID from a bad one?

Basically, the goal of the PID controller is to bring the craft’s rotation rate in all three axes to the rate that you’re commanding with your sticks. An error is computed which is the difference between your target rotation rate and the actual one measured by the gyroscopes, and the controller tries to bring this error to zero. If your multirotor appears uncontrollable, not locked in, or just wanders around. You have a bad tuning. If you have oscillations where the multirotor appears to bounce you have a bad tuning.

A video on how to recognize and correct different flight problems caused by PID settings is available here: https://www.youtube.com/watch?v=YNzqTGEl2xQ

0:00 To low P-Gain: hard to control, easy to overcorrect

0:45 Correct P-Gain: easy to control and fly

1:19 Too high P-Gain: Oscillates rapidly. Gains height easily. Hard to control height. Oscillating sound from motors.

1: 47 Too high I-Gain: Same as with too high P-Gain, but oscillates with a lower frequency.

2:06 Single axis tuning on a string; Setup: Set yaw PI-gain to zero and Roll/Pitch I-gain to zero

2:19 P-gain too low: Slow and imprecise stick response. Easy to turn by hand.

3:08 Increased P-gain: Sharper stick response. Harder to turn by hand

4:05 Good P-gain: Sharp stick response. Slight oscillations when releasing the stick. Hard to turn by hand

5:02 Too high P-gain: Oscillates rapidly. Oscillating sound from motors

5:36 Good P-gain, too low I-gain: Moves back to center when stick is released due to gravity. Easy to move by hand over long time

6:12 Good P-gain, good I-gain: Stays in position when stick is released. Very hard to move by hand over long time

6:55 Good P-gain, too high I-gain: Oscillates, but with a lower frequency than with too high P-gain

7:22 BONUS!

The rest of this course will try to explain how you actually tune your PID settings. By  following the steps outlined below you should be able to attain an approximate 80% tune  on your quad in just a few hours. Getting from 80% to close to 100% will be an iterative process, by documenting and repeating each step. Enabling the Blackbox flight data       recorder feature on your flight controller and examining the logs to see precisely what  the flight controller is doing will help tremendously to get you closer to a 100% tune.

I’ll be using various sources of information from around the web. To include but not limited to the following:

RCGroups.com Mini quad PID tuning from start to finish provided by joshuabardwell

CleanFlight GitHub resository https://github.com/cleanflight

Custom CMix http://blog.oscarliang.net/custom-motor-output-mix-quadcopter/

Alternative Tuning Methods:

There are other methods of tuning your PID settings. I’ll attempt to update this section with alternative methods as I locate them:

  1. From MultiWii website
  2. GTune

CleanFlight PID Controllers:

CleanFlight includes 6 PID controllers for you to choose from. This course is tuning and working with PID controller 1, “Rewrite”. The steps outlined below can be applied to any of the controllers included in CleanFlight. For more information about the PID Controllers please click here.

Cleanflight – What’s your favorite PID controller?

RCGroups.com Poll/Thread about what is your favorite PID Controller

Prerequisites:

  1. Naze32 flight controller or a CleanFlight supported FC, installed on your multirotor
  2. CleanFlight installed and running current version. (as of May 31, 2015, the current version is 1.9.0 Release notes and manual can be found here)
  3. PID controller 1 (PIDC#1) loaded in CleanFlight (Ref: CleanFlight)
    As per CleanFlight documentation: PID controller 1, "Rewrite"
    PID Controller 1 is a newer PID controller that is derived from the one in MultiWii 2.3 and later. It works better from all accounts, and fixes some inherent problems in  the way the old one worked. From reports, tuning is apparently easier on controller 1, and it tolerates a wider range of PID values well.
    
    Unlike controller 0, controller 1 allows the user to manipulate PID values to tune    reaction and stability without affecting yaw, roll or pitch rotation rates (which are tuned by the dedicated roll & pitch and yaw rate settings).
    
    In Angle mode, this controller uses the LEVEL "P" PID setting to decide how strong theauto-level correction should be. Note that the default value for P_Level is 90. This  is more than likely too high of a value for most, and will cause the model to be very unstable in Angle Mode, and could result in loss of control. It is recommended to     change this value to 20 before using PID Controller 1 in Angle Mode.
    
    In Horizon mode, this controller uses the LEVEL "I" PID setting to decide how much    auto-level correction should be applied. Level "I" term: Strength of horizon          auto-level. value of 0.030 in the configurator equals to 3.0 for Level P. Level "D"   term: Strength of horizon transition. 0 is more stick travel on level and 255 is more rate mode what means very narrow angle of leveling.
  4. Optional: Set Up a switch to be able to adjust P in flight (ref: Cleanflight – PID Switch Configuration Tutorial)Switch, Pitch & Roll P Adjustment
  5. Eliminate vibrations as much as possible in the mutlirotor. WARNING: You assume all risk associated with the following procedure: An easy way to determine how much vibration you have in your multirotor is to go to the motor test tab in CleanFlight. With the props on hold down your multirotor and spin up each motor individually, the trace on the screen will show you how much vibration each motor has. Here is a link to some tips for eliminating vibrations
  6. Try to have your COG (Center Of Gravity) as close as possible and aligned up with the center of the flight controller. This is not critical, but is considered a best practice to be relatively close.
  7. OPTIONAL: Blackbox flight data recorder (ref: CleanFlight Blackbox flight data recorder)
    This feature records your flight data information on every control loop iteration over a serial port to an external logging device to be recorded, or to a dataflash chip which is present on some flight controllers. Blackbox screen shot
  8.  OPTIONAL: Create a cmix if your multirotor is not square

This step is optional but will make tuning easier.
If your motors are not completely square, create a cmix for your layout according to these instructions. Cmix is not required, but if you have a cmix, it will cause your P gains to be much closer together on the pitch and roll axis. This makes it easier to tune, since you can basically tune both axes at the same time, instead of having to do each one separately.

 

Tuning procedure

  1. Load default PID values from PIDC#1 (ref: CleanFlight)

    PIDC#1 MultiWii  (rewrite) defaults

    PIDC#1 MultiWii (rewrite) defaults

    1. Change D to 15
    2. Change I to 0.020
  2. Establish the flyable range of P (ref: Edit Step Zero)

    1. The default value for both Pitch/Roll is 4.0 If you have a square multirotor or you followed the directions above to tune your CMix then you can tune Pitch & Roll together. We’ll assume you have tuned your CMix and or you have a symmetrical multirotor.
    2. Hover your quad and listen and look for high frequency oscillations. Since we have a CMix in place we can adjust both Pitch & Roll P values together.
    3. Increase P value for Pitch & Roll  till you see or hear oscillations. This can be accomplished by hovering the quad, stopping and connecting the computer and changing the values in CleanFlight or by following the procedure above in Prerequisites to setup a switch to increase your P values during flight.
    4. Starting at P=4.0 In this example oscillations were not  visible
    5. P=8.0 none.
    6. P=12.0 oscillations were audible in the motors.
    7. P=16.0 oscillations were visible in the multirotor.
    8. The value of P for both Pitch & Roll are set to 6.0 which is 50% of the range of the P value we established in our testing above. (P=4.0 to 16.0)
      Ref: PID Controller If the system must remain online, one tuning method is to first set I and D values to zero. Increase the P until the output of the loop oscillatesthen the P should be set to approximately half of that value for a "quarter        amplitude decay" type response. Then increase I until any offset is corrected in   sufficient time for the process. However, too much I will cause instability.       Finally, increase D, if required, until the loop is acceptably quick to reach its  reference after a load disturbance. However, too much D will cause excessive response and overshoot. A fast PID loop tuning usually overshoots slightly to reach the  setpoint more quickly; however, some systems cannot accept overshoot, in which casean over-damped closed-loop system is required, which will require a P setting      significantly less than half that of the P setting that was causing oscillation
  3. Basic tuning of I gain (ref: Basic tuning of I gain)

    1. A good test of I gain is to punch out hard, cut the throttle to about 25% and let the quad fall, then punch the throttle hard to arrest the fall. If the quad can maintain solid attitude then the I gain is probably not too low. If you see the angle of the quad changing then you need to increase I gain.
      1. The Pitch axis reacts differently from the Roll axis even though we have set up a CMix to account for the different spacing between motors. The difference is because of the weight distribution along the center of gravity of the Quad. The weight on the Pitch axis is further from the center of gravity then the Roll axis. Therefor you usually require more I gain on the Pitch axis then the Roll axis to account for the unequal weight distribution. (front to back verses side to side)
    2. If you notice your attitude changing when you did not input stick movement, or if you are constantly having to “nudge the copter back onto course”, that’s probably an indication that I is to low on the axis in question.
      1. TIP: you may experience some wondering if your transmitter flutters around center. This can be seen in the receivers tab in CleanFlight. For example with a range of 1000 to 2000, your center will be 1500. Watching the receiver tab in CleanFlight and you see the values jumping around the 1500 mark. Set Deadband in the CLI tab to 2 times the amount of fluctuation observed. For example jumping between 1500 & 1502 Set Deadband = 4
    3. If it is set too high, the craft may oscillate (but with slower oscillations than with P being set too high).
  4. Working up P gain (ref: Working up P gain)

    1. In step 2. above we established a P value for a stable hover. Next we want to tweak the P value for actual flight.
    2. Continue raising P gain up till you see oscillations. Also make note of your motor pitch and try to listen for oscillation in your motors.
  5. RC Rate, Pitch & Roll Rates (ref: Check and adjust rates)

    1. Explanations:
      1. RC Rate – sets the baseline stick sensitivity when using PIDC#1 (ref: CleanFlight)
      2. Pitch & Roll Rates –  For PID Controllers 1 and 2, this is an multiplier on overall stick sensitivity, like RC rate, but for roll and pitch independently. Stability (to outside factors like turbulence) is not reduced at stick extremes. A zero value is no increase in stick sensitivity over that set by RC rate above. Higher values increases stick sensitivity across the entire stick movement range. (ref: CleanFlight)
      3. Yaw Rate – In PID Controllers 1-4, it acts as a stick sensitivity multiplier, as explained above. (ref: CleanFlight)
    2. With P and I at close to optimal values, the quad is flyable enough that you should feel confident doing flips and rolls.
    3. Adjust expo to give you softness around the center stick but you can still do precision flying.
  6. Tuning TPA (ref: Tuning TPA)

    1. TPA stands for Throttle PID Attenuation. TPA basically allows an aggressively tuned multi-rotor (one that feels very locked in) to reduce its PID gains when throttle is applied beyond the TPA threshold/breakpoint in order to eliminate fast oscillations. TPA applies a PID value reduction in relation to full Throttle. It is used to apply dampening of PID values as full throttle is reached. (ref: CleanFlight)
    2. In order to determine where your TPA threshold should be, do some drop-and-catch maneuvers (where you cut throttle and let the quad fall, then punch hard to arrest the fall). Try to punch the throttle to a pre-determined position each time, slowly increasing the position until you find out about where the oscillations start to occur. Make a note of the throttle position.
    3. Do some high speed laps, paying attention to the throttle position in which high speed oscillations start to occur.
    4. Set your TPA threshold according to your testing in the 2 steps above. A customary setting is 0.70 which equates to 70% throttle and above.
  7. Fine-tuning P & D (ref: Fine-tuning P & D)

    1. When tuning P & I they for the most part tune independently of each other.
    2. Unfortunately, P is interrelated with D, which complicates the search for the best combination of values. Ideally, the way it works is that increased D gain “damps” the effect of P. If P is changing rapidly, D will counteract that change. This means that in cases where P would usually jerk the craft around, overshoot, and oscillate, increased D can reign it in.
    3. Excess D can also manifest as the quad changing altitude spontaneously during hover, even though the throttle hasn’t moved.

 

Additional information:

The Roll of the Gyroscope & Accelerometer

Gyroscope

A gyroscope measure angular velocity, in other words the rotational speed around the three axis. Acro mode uses only the gyro.

Accelerometer

In Simple words the ACC can sense the orientation of the multicopter. It is required for the self-level flight feature. The ACC sensor is also required in the altitude hold feature (along with Baro or sonar), estimates the velocity of the quadcopter in the vertical direction. Autolevel modes (Angle & Horizon) use the gyro and accelerometer. In CleanFlight click on Calibrate Accelerometer in the Setup tab. Make sure you have your multirotor sitting on a level surface prior to calibration.

Trim

You can’t trim the transmitter because the sticks are interpreted differently in acro vs. autolevel modes. In acro mode, a stick position corresponds to a rate of angular change (e.g. pitch forward at a rate of 10 degrees per second). In angle mode, a stick position corresponds to a given angular position (e.g. pitch forward 10 degrees from vertical and stay there). So let’s say the stick is trimmed pitch forward to correct backwards drift in autolevel mode. Now you switch to acro mode and the copter will begin to pitch forward and keep pitching forward in a slow front flip.

If you have drift in acro mode, you should work on your tune (e.g. maybe increase I gain, or decrease vibration, or change your soft filters to filter out vibration). NOTE: Soft Filters are not included in version 1.9.0, I believe they will be included in the next build of CleanFlight. More information is available here. If you have drift in autolevel mode, you should use acc trim in the FC to deal with it(see How to trim your Accelerometer below). In theory, if you only ever flew in autolevel mode, you could get away with using transmitter trims, but it’s a bad habit, because the second you switch to acro mode, the copter is going to be much harder to fly.

The exception to this rule is the yaw axis. The yaw axis only ever uses the gyro, even in autolevel modes. So if you have yaw drift, it’s acceptable to tune it out with transmitter trim. But really, you should first try to figure out what’s wrong with your copter or your tune that the FC can’t hold heading reliably, because it’s probably hurting you elsewhere, not just in yaw.

Therefore the correct way to Calibrate is to use Accelerometer trims, which brings us to our next point.

How to trim your Accelerometer

In order to have a stable hover in an Autolevel mode (Angle or Horizon) you need to trim the Accelerometer. If you recall above the Accelerometer is not used in Acro mode. When you activate an Autolevel mode and your multirotor moves you need to trim your accelerometer as detailed below.

There are 2 methods to accomplish this. Method 1 allows you to adjust your trim in 1  step increments at a time similar to how you would trim your radio. Method 2 is more  of an automatic trim. The tried and true method is Method 1. Method 2 is provided for reference

Using the diagram below as a reference:

Clean Flight Stick Positions

Method 1 – Manual calibration

  1. Enter autolevel mode (Angle or Horizion).
  2. Arm the copter and take off. Try to maintain level flight, if level is not perfect you will have to counteract the error with some stick input. Make a mental note of the corrective action required for a stable hover.
  3. Now land the multicopter and disarm motors.
  4. Now with motors disarmed, move the throttle to maximum. With the throttle at maximum, the copter is waiting for command input to adjust the ACC level.
  5. If the copter was pitching forward (going away from you), then:
    • a. Pull full back on the pitch.
    • b.Then return to center
    • c.Repeat a number of times, the more times you repeat the more correction it will make but it only does it in a single small increments for each “full back, and return to center” sequence. Similar to each tick when trimming your transmitter. Repeating 3-4 times is not really noticeable (only a slight correction). You may have to start with 10-12 increments for the first correction. Then test fly, and repeat the process with another 3-5 increments.
  6. Now you can do the roll, same process:
    • a.All the way left or right, then return to center
    • b.Only do a correction for a single direction at a time…diagonal correction input does not work.
  7. After doing a number of increments for Roll and Pitch. With the P/R stick at center, return the throttle back to full low. Rearm the motors and test fly. Repeat until the copter maintains level.
  8. Do not do the ACC calibration again or you will lose this trim calibration. The copter will remember your calibration settings so once trimmed your auto-level should perform perfectly and you won’t have to repeat this tutorial until you upgrade your Firmware.

Method 2 – Inflight ACC calibration

I’ve attempted to calibrate with this procedure and I was not successful. When disarming in flight, the motors would stop and the quad fell out of the sky. If anybody has any firsthand experience with this procedure, please let me know.

How it works (overview)
-Enable INFLIGHT_ACC_CAL
-fly
-trim/get stable
-save deviation
-land
-finished

Activation with stick combo

Preparation:
1. In CleanFlight, Configuration tab, Enable INFLIGHT_ACC_CAL in Other Features
2. Plug the power and wait for the init to finish, the ACC has to be calibrated at least once since you cleared the eeprom.

Procedure:
1. Do the following stick combination as depicted in diagram above (throttle low)+(yaw left)+(pitch forward)+(roll right)
2. You will hear two beeps that indicate that the function is armed (to disarm it simply repeat the combo – you will hear three beeps)
3. Start your copter and get airborne
4a) In acro mode: get your copter level and make sure it does not drift
4b) in level mode: get you copter level using the trims on your tx until it does not drift
5. Now disarm the copter with the aux switch – you will hear a beep:the measurement is finished (don’t worry, a failsafe feature prevents it from shutting down if throttle is above minthrottle)
6. You may rearm the copter now to prevent a crash while landing
7. Land the copter and disarm it, you will hear a long beep: The values have been stored in eeprom
8. If you have choosen 4 b): TAKE BACK ALL THE TRIMS BEFORE TAKEOFF
9. Get airborne again – the copter should now be level without drift
10. Repeat if neccesary


Comments

CleanFlight PID Tuning — 2 Comments

Leave a Reply