Skip to content

Instantly share code, notes, and snippets.

@Benricheson101
Created May 10, 2025 03:21
Show Gist options
  • Select an option

  • Save Benricheson101/97d8516b3ad4b7b377452e50f5855ec4 to your computer and use it in GitHub Desktop.

Select an option

Save Benricheson101/97d8516b3ad4b7b377452e50f5855ec4 to your computer and use it in GitHub Desktop.
export class PIDController {
#integral = 0;
#prevError = 0;
constructor(
readonly opts: {
/** setpoint. the target value */
sp: number;
// dt: number;
/** proportional gain */
kp: number;
/** integral gain */
ki: number;
/** derivative gain */
kd: number;
}
) {}
update(val: number, dt = 60) {
const {kp, ki, kd, sp} = this.opts;
const error = sp - val;
const integral = this.#integral + (error * dt);
const derivative = (error - this.#prevError) / dt;
const output = (kp * error) + (ki * integral) + (kd * derivative);
console.log({error, integral, derivative, output, opts: this.opts});
this.#prevError = error;
this.#integral = integral;
return output;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment