How does PID algorithm work?

29 Dec 2021

What does PID try to solve in general? Simply put, PID is a way to answer the question - how much “force” to apply to reach a target state from one state?

Some examples:

  1. Adjust the power of an AC to reach a temperature
  2. Apply throttle or brake to reach a speed
  3. Adjust the motor RPM of a drone, to reach certain rotation speed

Some concepts:

  1. The “force”: output of PID system, a.k.a PID sum, it's literally the P/I/D three components added together.
  2. The target state: setpoint

Some facts:

  1. It’s a iterative algorithm, we need to reevaluate the output constantly based on current status
  2. The higher the frequency the smoother the control signal would be (subject to limitations on the signal execution component - the actuator)

The following is a block diagram of PID algorithm

PID algorithm diagram



The following is a simple implementation of the algorithm

    const dt = time - this._prevTime;
    const error = setpoint - measurement;

    this._i += error * dt;

    const p = this.kp * error;
    const i = this.ki * this._i;
    const d = this.kd * (measurement - this._prevMeasurement) / dt;
    const f = this.kf * (command - this._prevCommand) / dt;

    this._prevCommand = command;
    this._prevTime = time;

    return (p + i + d + f);