Simvik

Derivative without the kick

Take the derivative of the measurement, not the error, so setpoint steps do not spike the output. A medium embedded C problem (PID control), run and graded…

medium · PID control · pid · control · fixed-point

A textbook PID controller takes the derivative of the error. When the setpoint jumps, the error jumps, its derivative is huge for one step, and the output spikes: derivative kick. Since the setpoint is constant between changes, the derivative of the error equals minus the derivative of the measurement, so practical controllers use the measurement instead.

Write pid_step(p, setpoint, measured), called at a fixed rate:

  • error = setpoint − measured; add it to integral,
  • output = (kp × error + ki × integral − kd × (measured − prev_measured)) / 100,
  • on the first call there is no previous measurement: use the current one, so the derivative term is 0,
  • remember measured for the next call.

Starter code

int32_t pid_step(pid_t *p, int32_t setpoint, int32_t measured) {
  static int32_t prev_error = 0;
  int32_t error = setpoint - measured;
  p->integral += error;
  int32_t out = (p->kp * error + p->ki * p->integral + p->kd * (error - prev_error)) / 100;
  prev_error = error;
  return out;
}

Example tests

Steady setpoint, moving measurement

pid_t p = { 200, 10, 300 };
int32_t sp[] = { 100, 100, 100, 100 }, m[] = { 0, 20, 50, 70 };
run(&p, sp, m, 4);

Expected output:

210 118 33 26

A setpoint step does not kick

pid_t p = { 200, 10, 300 };
int32_t sp[] = { 50, 50, 150, 150 }, m[] = { 50, 50, 50, 60 };
run(&p, sp, m, 4);

Expected output:

0 0 210 169

Learn it first

  • PID control · Feedback loops, the three terms, anti-windup and tuning.

More PID control problems