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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| #include "pid.h" PIDController motor_pid;
float PID_update(PIDController *pid, float setpoint, float measurement) {
float error = setpoint - measurement;
float proportional = pid->Kp * error;
pid->integrator = pid->integrator + 0.5f * pid->Ki * pid->T * (error + pid->prevError);
if (pid->integrator > pid->limMaxInt) {
pid->integrator = pid->limMaxInt;
} else if (pid->integrator < pid->limMinInt) {
pid->integrator = pid->limMinInt;
}
pid->differentiator = -(2.0f * pid->Kd * (measurement - pid->prevMeasurement) + (2.0f * pid->tau - pid->T) * pid->differentiator) / (2.0f * pid->tau + pid->T);
pid->out = proportional + pid->integrator + pid->differentiator;
if (pid->out > pid->limMax) {
pid->out = pid->limMax;
} else if (pid->out < pid->limMin) {
pid->out = pid->limMin;
}
pid->prevError = error; pid->prevMeasurement = measurement;
return pid->out;
}
|