// PID 算法参数
float Kp = 0.5; // 比例系数
float Ki = 0.1; // 积分系数
float Kd = 0.05; // 微分系数
float setPoint = 585.0; // 设定值
float processValue; // 过程值
float error; // 误差
float integral; // 积分项
float derivative; // 微分项
float prevError; //当前误差与上一误差的差值
float shuchuzhi; // 控制输出值
void calculatePID() {
error = setPoint - processValue;
integral += error;
derivative = error - prevError;
float output = Kp * error + Ki * integral + Kd * derivative; //计算公式
prevError = error;
shuchuzhi = shuchuzhi + output;
shuchuzhi = constrain(shuchuzhi, 0, 255);
}
void setup(void){
Serial.begin(9600);
pinMode(3, OUTPUT);
pinMode(A0, INPUT);
}
void loop() {
calculatePID();
analogWrite(3, shuchuzhi);
processValue = analogRead(A0);
Serial.print(analogRead(A0));
Serial.print(" ");
Serial.print(setPoint);
Serial.print(" ");
Serial.println(shuchuzhi);
}