Project files
README.md
Machine-translated by Robotheca from the original in Chinese (opens in a new tab). License: MIT (opens in a new tab).
Cascade PID
Single-loop PID is suitable for linear systems. When the output and the controlled variable have a linear relationship, single-loop PID can achieve good results. However, quadcopters are not linear systems. Modern scholars believe that quadcopters can usually be simplified as a second-order damped system. Why are quadcopters not linear systems? First, the output voltage and motor speed are not proportional. Second, the propeller speed and lift have a squared relationship. Therefore, single-loop PID is difficult to achieve good results on quadcopters—it can fly, but not well.
To solve this problem, we propose the cascade PID method.
The implementation of digital PID control must use numerical approximation methods.
When the sampling period is sufficiently short, integration can be replaced by summation, and differentiation can be replaced by backward difference, converting the analog PID into a difference equation.
Digital PID algorithms are generally divided into position-type control algorithms and incremental-type control algorithms.
Pseudocode
Outer-loop PID
-
Calculate the angle error for the controlled axes (Pitch, Roll, Yaw) (actual angle - desired angle)
-
Integral term
- Accumulate the error result (replace integration with summation)
- Apply integral clamping to the accumulated result
-
Derivative term
- Subtract the previous angle value from the current angle value (backward difference)
-
Outer-loop output
- Proportional gain
P× current error + Integral gainI× integral term + Derivative gainD× derivative term
- Proportional gain
-
-
Save the previous angle value
Inner-loop PD
-
Proportional term
- Outer-loop output + the axis's angular velocity × 3.5
-
Derivative term
- The axis's angular velocity - the previous angular velocity of that axis (backward difference)
-
Inner-loop output
- Proportional gain
p× proportional term + Derivative gaind× derivative term
- Proportional gain
- Store angular velocity
Code
First, define the structure and structure pointer, encapsulate the large number of variables used in the calculation process, and parse and utilize them in dedicated functions.
typedef struct {
float InnerLast; //Save the old value of the inner loop for backward difference
float OutterLast; //Save the old value of the outer loop for backward difference
float *Feedback; //Feedback data, real-time angle data
float *Gyro; //Angular velocity
float Error; //Error value
float p; //Proportional term (shared by inner and outer loops)
float i; //Integral term (used only for outer loop)
float d; //Derivative term (shared by inner and outer loops)
short output; //PID output, used to modify PWM value, 2 bytes
__IO uint16_t *Channel1;//PWM output, channel 1
__IO uint16_t *Channel2;//PWM output, channel 2
} pid_st, *pid_pst;
void pid_SingleAxis(pid_pst temp, float setPoint) {
temp->Error = *temp->Feedback - setPoint;
//Outter Loop PID
temp->i += temp->Error;
if (temp->i > PID_IMAX) temp->i = PID_IMAX;
else if (temp->i < PID_IMIN) temp->i = PID_IMIN;
temp->d = *temp->Feedback - temp->OutterLast;
temp->output = (short)(OUTTER_LOOP_KP * (temp->Error) + OUTTER_LOOP_KI * temp->i + OUTTER_LOOP_KD * temp->d);
temp->OutterLast = *temp->Feedback; //Save Old Data
//Inner Loop PD
temp->p = temp->output + *temp->Gyro;
temp->d = *temp->Gyro - temp->InnerLast;
temp->output = (short)(INNER_LOOP_KP * temp->p + INNER_LOOP_KD * temp->d);
if (*temp->Channel1+temp->output > THROTTLE_MAX) *temp->Channel1 = THROTTLE_MAX;
else if (*temp->Channel1+temp->output < THROTTLE_MIN) *temp->Channel1 = THROTTLE_MIN;
else *temp->Channel1 += (short)temp->output;
if (*temp->Channel2-temp->output > THROTTLE_MAX) *temp->Channel2 = THROTTLE_MAX;
else if (*temp->Channel2-temp->output < THROTTLE_MIN) *temp->Channel2 = THROTTLE_MIN;
else *temp->Channel2 -= (short)temp->output;
temp->InnerLast = *temp->Gyro;
}
Tuning PID Parameters
-
Adjust the PID parameters based on the aircraft's takeoff throttle setting; otherwise, even if the aircraft is stable during bench testing ("roasting the quad"), it may oscillate when flying.
-
The inner-loop parameters are the most critical! Ideal inner-loop parameters can closely follow the control input (in rate mode, i.e., angular velocity control mode). Near the balanced position (around ±30 degrees), when the stick is abruptly deflected, the aircraft should respond quickly; when the stick returns to center, the aircraft should stop immediately (with minimal rebound or oscillation).
2.1. First, modify the program to remove the angle outer loop and use the stick deflection as the inner loop's setpoint (rate mode, called ACRO mode in APM and Manual mode in DJI).
2.2. Add P gain. If P is too small, the aircraft will feel "soft," making it difficult to correct angular velocity errors, and the response to stick deflection will be poor. If P is too large, the aircraft will oscillate near the balanced position, and oscillations will occur when the stick returns to center or when disturbed (e.g., by a sudden external force). A suitable P value will provide good response to stick deflection without excessive oscillation, but the aircraft may still rebound several times after the stick returns to center (due to lack of D).
2.3. Add D gain. D has a significant effect: it speeds up the response to stick deflection and most importantly, effectively suppresses oscillations after the stick returns to center. However, an excessively large D can cause twitching when rolling and pitching simultaneously (even if it performs well during bench testing). If this happens, return to bench testing to reduce D, and P should also be reduced accordingly. After adjusting D, you can increase P again, aiming for a response that follows stick deflection.
2.4. Add I gain. You will notice the control feel becomes smoother. In the author's bench-testing setup, the quadcopter's center of gravity is higher than the rotation axis, meaning that once the quadcopter deviates from level, gravity will cause it to continue tilting. The I term helps correct this by counteracting the gravitational effect within a certain angle range (around 30 degrees). For example, after deflecting the stick to tilt the aircraft, when the stick returns to center, the aircraft should stop immediately. Without I or with too small an I, the aircraft will continue rotating due to gravity.
-
The angle outer loop has only one parameter: P. Enable the outer loop (called Stabilize mode in APM and Attitude mode in DJI). Stick deflection will correspond to the desired angle. Tuning P is straightforward: if it's too small, the response to stick deflection will be sluggish; if it's too large, oscillations will occur when the stick returns to center. Aim for a suitable response speed.
-
At this point, the bench-testing ("roasting the quad") should perform well, but the performance during simultaneous roll and pitch control may still be uncertain and could exhibit twitching (due to the combined control inputs, especially large D values). If twitching occurs, reduce the PD values; the I value generally does not need adjustment.
-
After adding yaw correction parameters (directly set the double-loop parameters: the angle outer loop P should be similar to roll, the inner loop P slightly larger than roll, I similar to roll, and D can be omitted initially), test the correction and stick direction while holding the aircraft in hand before attempting a flight (flying is dangerous!!! Choose a spacious, windless indoor area, fly at a height of 1 meter—too low may cause ground effect interference, too high makes it hard to observe attitude and increases the risk of damage. Avoid crowds. In case of any issues, immediately cut the throttle!!!).
5.1. During test flights, observe the following aspects. After proper tuning, the aircraft should not exhibit large oscillations at the balanced position:
5.2. Check for small-amplitude oscillations at the balanced position (which may be caused by excessive airframe vibration leading to attitude estimation errors, or excessive fluctuations in the inner-loop D term). For the former, enhance vibration damping measures, such as attaching the sensor to the frame with 3M adhesive, or using a "damping plate" sandwiched between two layers of 3M foam (note: ferromagnetic damping plates can interfere with magnetometer readings). For the latter, try lowering the cutoff frequency of the D-term filter.
5.3. Observe the response speed to stick deflection and the recovery speed after the stick returns to center.
5.4. Test large, abrupt stick inputs in all directions (remember to test directions like right-front and left-back) and check for oscillations upon returning the stick to center. If oscillations occur, try reducing the inner-loop PD values, which may also be caused by excessive stick inputs in mixed-control directions like "right-front."
-
After tuning roll and pitch, you can adjust the yaw parameters. The criteria for suitable parameters are the same: quick response to stick deflection, and the aircraft should stop rotating immediately when the stick returns to center (the role of the D term).
References
[1] Wang Song, Li Xinjun, Liang Jianhong, Pu Li. Design of Embedded Autopilot for Micro and Small Robots[J]. Journal of Beijing University of Aeronautics and Astronautics, 2005, (07).
[2] Ye Qing; Xiong Maohua; Predictive-PID Cascade Control in Fermentation Process[J]. Microcomputer Information, 2006, (22), 73-75.
[3] Chen Xin, Yang Yidong, Zhang Min. Research on Attitude Intelligent PID Control of Unmanned Aerial Vehicle[J]. Journal of Nanjing University of Aeronautics and Astronautics, 2003, (06).
[4] Xu Minxin, Wang Lv. Research and Application of Miniaturization of Airborne Sensors for Unmanned Aerial Vehicles[J]. Data Acquisition and Processing.
[5] PID Tuning of Quadrotor UAV Flight Controller (Referencing APM Program) via CSDN (opens in a new tab)
Files by @but0n, at commit 9d3f6a4, read from GitHub in your browser. Hardware license: MIT; software license: MIT. Robotheca doesn't review code: read it before running it.