PID Control Algorithm: From Continuous to C Language Digital Control

Hello everyone, I am the Intelligence Guy~

Today, I summarized the PID algorithm, from continuous algorithm formulas to discrete digitalization~

Whether it’s a drone hovering in place, a balance scooter maintaining an upright posture, or a water heater accurately maintaining a set temperature, they all rely on thePID control algorithm, a powerful tool.

As the most classic control algorithm in embedded development, PID has become the “universal controller” in the hands of engineers due to its simple structure and strong adaptability. I remember a survey that indicated PID can solve about 90% of control problems. Therefore, this article willtake you from mathematical principles to code implementation, helping you thoroughly master the digital implementation methods of PID and have fun with it.

1. Analysis of PID Control Principles

PID = Proportional (P) + Integral (I) + Derivative (D)Proportional Term (P): Quick response to real-time deviation<span><span>Output ∝ Current Error</span></span>, quickly reducing the deviation but may cause oscillationFormula:<span><span>P_out = Kp * e(t)</span></span>

Integral Term (I): Eliminates steady-state error<span><span>Output ∝ Accumulated Error</span></span>, eliminates system steady-state error but may cause overshootFormula:<span><span>I_out = Ki * ∫e(t)dt</span></span>

Derivative Term (D): Predicts future trends<span><span>Output ∝ Rate of Change of Error</span></span>, suppresses overshoot but amplifies noiseFormula:<span><span>D_out = Kd * de(t)/dt</span></span>

Continuous Domain Formula:<span><span>u(t) = Kp*e(t) + Ki*∫e(t)dt + Kd*(de(t)/dt)</span></span>

2. Digital Transformation: From Continuous to Discrete

In digital systems, we need to discretize the continuous formulas. Let the sampling period beT, using theBackward Difference Method:

  1. Discretization of the Integral Term:<span><span>∫e(t)dt ≈ T * Σe(k)</span></span>Accumulating historical errors:<span><span>sum_error += e(k)</span></span>

  2. Discretization of the Derivative Term:<span><span>de(t)/dt ≈ [e(k) - e(k-1)] / T</span></span>

Discrete PID Formula (Position Form):<span><span>u(k) = Kp*e(k) + Ki*T*sum_error + Kd*[e(k)-e(k-1)]/T</span></span>

3. C Language Implementation (Based on STM32)

typedef struct {
    float Kp, Ki, Kd;   // PID parameters
    float T;            // Sampling period
    float max_output;   // Output limit
    float integral;     // Integral accumulation
    float last_error;   // Last error
} PID_Controller;

void PID_Init(PID_Controller *pid, float Kp, float Ki, float Kd, float T, float max_out) {
    pid->Kp = Kp;
    pid->Ki = Ki * T;  // Pre-multiply by sampling period
    pid->Kd = Kd / T;  // Pre-divide by sampling period
    pid->T = T;
    pid->max_output = max_out;
    pid->integral = 0;
    pid->last_error = 0;
}

float PID_Calculate(PID_Controller *pid, float setpoint, float feedback) {
    float error = setpoint - feedback;
    
    // Integral term (with anti-windup)
    pid->integral += error;
    if(pid->integral > pid->max_output) pid->integral = pid->max_output;
    elseif(pid->integral < -pid->max_output) pid->integral = -pid->max_output;

    // Derivative term (optional: low-pass filter on derivative term)
    float d_error = error - pid->last_error;
    
    // Calculate output
    float output = pid->Kp * error 
                 + pid->Ki * pid->integral 
                 + pid->Kd * d_error;
    
    // Output limit
    if(output > pid->max_output) output = pid->max_output;
    elseif(output < -pid->max_output) output = -pid->max_output;
    
    pid->last_error = error;
    return output;
}

4. PID Parameter Tuning Methods

Most blind tuning rules:First adjust P, then I, and finally add D

  1. Trial and Error Method (suitable for simple systems, experienced engineers can directly tune to achieve satisfactory results)P: Increase from small to large until the system exhibits sustained oscillationI: Add appropriately to eliminate steady-state errorD: Suppress overshoot and enhance stability

  2. Critical Proportional Method (Ziegler-Nichols, this method is recommended for more professional tuning)• Set Ki=0, Kd=0, gradually increase Kp to the critical oscillation point• Record the critical gain Ku and oscillation period Tu• Set parameters according to the table below:

    Control Type Kp Ki Kd
    P 0.5*Ku 0 0
    PI 0.45*Ku 0.54*Ku/Tu 0
    PID 0.6*Ku 1.2*Ku/Tu 0.075KuTu
  3. Empirical Parameter Ranges (for most systems, many parameters are quite similar)• Temperature Control: P(2-15), I(0.05-0.5), D(2-15)• Motor Control: P(0.1-1), I(0.01-0.1), D(0-0.1)

Tuning Tips:• Oscillation occurs: Decrease Kp or Kd• Slow response: Increase Kp• Steady-state error: Increase Ki• Sensitive to noise: Decrease Kd or add low-pass filtering

5. Issues to Note

  1. Integral Windup: When the error persists, the integral term becomes too largeSolutions:• Integral limiting• Integral separation (stop integration when the error is large)

  2. Derivative Noise: Measurement noise causes control output jitterSolutions:• Apply low-pass filtering to the derivative term

    // First-order low-pass filter example
    d_filter = 0.2*d_error + 0.8*d_filter;
    

The PID algorithm is like the “LEGO blocks” of the control field, cleverly combining three parameters to meet most control needs, which is very ingenious~

PID Control Algorithm: From Continuous to C Language Digital Control

END

Source:Embedded Intelligence Bureau

Copyright belongs to the original author, please contact for deletion if there is any infringement.Recommended ReadingThe company used pirated AD software and received a lawyer’s letter…If your code is fast and good, you are a fool!!!Why is hardware more difficult than software, yet hardware engineers earn less than software engineers?→ Follow to avoid getting lost←

Leave a Comment