Files
Motor_v2/Robot_V2/Algorithm/pid.cpp
T

91 lines
2.1 KiB
C++
Raw Normal View History

2025-10-30 20:20:14 +08:00
#include "pid.h"
2025-11-06 02:07:15 +08:00
#define _constrain(amt, low, high) \
((amt) < (low) ? (low) : ((amt) > (high) ? (high) : (amt)))
#include "Can.h"
#include "config.h"
2026-01-24 01:50:39 +08:00
#include <algorithm>
#include <cmath>
2025-10-30 20:20:14 +08:00
extern CAN_transmiter CAN0_transmiter;
2025-10-30 20:20:14 +08:00
PIDController::PIDController(float P, float I, float D, float ramp, float limit)
2025-11-06 02:07:15 +08:00
: P(P), I(I), D(D), output_ramp(ramp) // PID控制器加速度限幅
,
limit(limit) // PID控制器输出限幅
,
error_prev(0.0f), output_prev(0.0f), integral_prev(0.0f) {}
2025-10-30 20:20:14 +08:00
// PID 控制器函数
2025-11-06 02:07:15 +08:00
float PIDController::operator()(float error) {
// P环
float proportional = P * error;
2025-11-06 02:07:15 +08:00
// Tustin 散点积分(I环)
// 添加积分限幅,防止积分饱和
float integral =
integral_prev + I * TIME_SLICE * 0.5f * (error + error_prev);
2025-11-06 02:07:15 +08:00
integral = _constrain(integral, -limit, limit);
2025-11-06 02:07:15 +08:00
// D环(微分环节)
float derivative = D * (error - error_prev) / TIME_SLICE;
2025-11-06 02:07:15 +08:00
// 将P,I,D三环的计算值加起来
float output = proportional + integral + derivative;
output = _constrain(output, -limit, limit);
2025-10-30 20:20:14 +08:00
// 输出斜坡限制
// 简化的斜坡限制(单行逻辑)
if (output_ramp > 0) {
float max_delta = output_ramp * TIME_SLICE;
output = output_prev +
fmaxf(-max_delta, fminf(max_delta, output - output_prev));
}
2025-11-06 02:07:15 +08:00
// 保存值(为了下一次循环)
integral_prev = integral;
output_prev = output;
error_prev = error;
return output;
}
/**
* @brief 设置PID参数
*
* @param P: P参数
* @param I: I参数
* @param D: D参数
* @return void
*/
void PIDController::set_PID(float P, float I, float D) {
this->P = P;
this->I = I;
this->D = D;
}
/**
* @brief 设置P参数
*
* @param P: P参数
* @return void
*/
void PIDController::set_P(float pp) { this->P = pp; }
/**
* @brief 设置输出限幅
*
* @param limit: 输出限幅
* @return void
*/
void PIDController::set_limit(float limit) { this->limit = limit; }
/**
* @brief 重置PID控制器状态
*
* @return void
*/
void PIDController::reset() {
error_prev = 0.0f;
output_prev = 0.0f;
integral_prev = 0.0f;
}