#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct {
float SetSpeed;
float LastLocation;
float err_now_0;
float err_last_1;
float Kp;
float Ki;
float Kd;
float output;
float integral_sum;
}PID;
PID pid;
void
PID_Config(PID *pid)
{
(*pid).SetSpeed = 0.0;
(*pid).LastLocation = 0.0;
(*pid).err_now_0 = 0.0;
(*pid).err_last_1 = 0.0;
(*pid).output = 0.0;
(*pid).integral_sum = 0.0;
(*pid).Kp = 0.4;
(*pid).Ki = 0.2;
(*pid).Kd = 0.2;
}
float
PID_SetSpeed(PID *pid, float speed)
{
float index;
(*pid).SetSpeed = speed;
(*pid).err_now_0 = (*pid).SetSpeed-(*pid).LastLocation;
if (abs((*pid).err_now_0) > 200){
index = 0.0;
} else if (abs((*pid).err_now_0 < 180)) {
index= 1.0;
(*pid).integral_sum += (*pid).err_now_0;
}else {
index = (200-abs((*pid).err_now_0)) / 20; /*180-200 is dynamic*/
(*pid).integral_sum += (*pid).err_now_0;
}
(*pid).output = (*pid).Kp * (*pid).err_now_0 + index * (*pid).Ki * (*pid).integral_sum + (*pid).Kd * ((*pid).err_now_0 - (*pid).err_last_1);
(*pid).err_last_1 = (*pid).err_now_0;
(*pid).LastLocation = (*pid).output * 1.0;
return (*pid).output;
}
int
main(int argc, char *argv[])
{
int count = 0;
float speed;
PID_Config(&pid);
while (count < 1000) {
speed = PID_SetSpeed(&pid, 200.0);
printf("%f \n",speed);
count++;
}
return 0;
}