-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid.js
44 lines (35 loc) · 959 Bytes
/
pid.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// PID Object
class PID {
constructor(Kp, Ki, Kd) {
this.Kp = Kp;
this.Ki = Ki;
this.Kd = Kd;
this.prevError = 0.0;
this.integral = 0.0;
}
calculate(setpoint, measuredValue, dt) {
// Calculate error
const error = setpoint - measuredValue;
// Proportional term
const Pout = this.Kp * error;
// Integral term
this.integral += error * dt;
const Iout = this.Ki * this.integral;
// Derivative term
const derivative = (error - this.prevError) / dt;
const Dout = this.Kd * derivative;
// Calculate total output
const output = Pout + Iout + Dout;
// Save error for next iteration
this.prevError = error;
return output;
}
reset() {
this.prevError = 0.0;
this.integral = 0.0;
this.output = 0;
}
clearKi() {
this.integral = 0.0;
}
}