模糊PID控制
// 模糊PID结构体
typedef struct {
float Kp, Ki, Kd; // PID参数
float error, last_error; // 当前和上次误差
float error_rate; // 误差变化率
float output; // 输出
} Fuzzy_PID;
// 模糊规则表
const float fuzzy_rule[3][3] = {
{0.3, 0.5, 0.7}, // 误差大
{0.5, 0.7, 0.9}, // 误差中
{0.7, 0.9, 1.1} // 误差小
};
void fuzzy_pid_update(Fuzzy_PID* pid, float setpoint, float feedback) {
pid->error = setpoint - feedback;
pid->error_rate = pid->error - pid->last_error;
// 模糊化处理
int e_level = fuzzify_error(pid->error);
int ec_level = fuzzify_error_rate(pid->error_rate);
// 查表获取调整因子
float adjust_factor = fuzzy_rule[e_level][ec_level];
// 自适应调整参数
pid->Kp *= adjust_factor;
pid->Ki *= adjust_factor;
pid->Kd *= adjust_factor;
// 执行PID计算
pid->output = pid->Kp * pid->error +
pid->Ki * pid->error_integral +
pid->Kd * pid->error_rate;
pid->last_error = pid->error;
} |