实现PID控制
编写PID控制算法
c
复制
编辑
typedef struct {
float Kp;
float Ki;
float Kd;
float prev_error;
float integral;
} PIDController;
PIDController pid = {1.5, 0.05, 0.5, 0, 0}; // 设定PID参数
int16_t PID_Compute(int16_t target, int16_t actual) {
float error = target - actual;
pid.integral += error;
float derivative = error - pid.prev_error;
pid.prev_error = error;
int16_t output = (int16_t)(pid.Kp * error + pid.Ki * pid.integral + pid.Kd * derivative);
// 限制PWM范围
if (output > PWM_DUTY_MAX) output = PWM_DUTY_MAX;
if (output < 0) output = 0;
return output;
}
|