Created
August 19, 2024 16:56
-
-
Save aib/6eb3277bf5be40d4353edfdb3416d4c2 to your computer and use it in GitHub Desktop.
JS PID Controller
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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