Skip to content

Instantly share code, notes, and snippets.

@aib
Created August 19, 2024 16:56
Show Gist options
  • Save aib/6eb3277bf5be40d4353edfdb3416d4c2 to your computer and use it in GitHub Desktop.
Save aib/6eb3277bf5be40d4353edfdb3416d4c2 to your computer and use it in GitHub Desktop.
JS PID Controller
class PIDController
{
constructor(Kp, Ki, Kd) {
this.Kp = Kp;
this.Ki = Ki;
this.Kd = Kd;
this.deltaError = 0;
this.sumError = 0;
this.lastError = 0;
this.lastT = this.getNow();
}
run(error) {
const now = this.getNow();
const deltaT = this.lastT - now;
this.lastT = now;
if (deltaT != 0) {
this.deltaError = (error - this.lastError) / deltaT;
}
this.sumError += error * deltaT;
this.lastError = error;
return this.Kp*error + this.Ki*this.sumError + this.Kd*this.deltaError;
}
getNow() {
return performance.now();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment