- 升级ARM::CMSIS从4.5.0到6.1.0版本 - 添加ARM::CMSIS-DSP@1.16.2依赖包 - 升级GigaDevice::GD32C10x_DFP从1.0.1到1.5.0版本 - 移除FOC.cpp中未使用的systick.h头文件 - 移除pid.cpp中未使用的<algorithm>头文件 - 更新GD32C10x固件库至V1.7.0版本(2026-01-30) - 修复ADC驱动中的无符号整数运算问题 - 优化BKP、CAN、CTC等外设驱动中的FlagStatus返回逻辑 - 改进CAN驱动的消息发送和传输停止函数实现 - 修复CRC、DMA、FMC等驱动中的数据类型和变量声明问题 - 清理和修正各驱动文件中的文档注释
90 lines
2.0 KiB
C++
90 lines
2.0 KiB
C++
#include "pid.h"
|
|
#define _constrain(amt, low, high) \
|
|
((amt) < (low) ? (low) : ((amt) > (high) ? (high) : (amt)))
|
|
#include "Can.h"
|
|
#include "config.h"
|
|
#include <cmath>
|
|
|
|
extern CAN_transmiter CAN0_transmiter;
|
|
PIDController::PIDController(float P, float I, float D, float ramp, float limit)
|
|
: 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) {}
|
|
|
|
// PID 控制器函数
|
|
float PIDController::operator()(float error) {
|
|
// P环
|
|
float proportional = P * error;
|
|
|
|
// Tustin 散点积分(I环)
|
|
// 添加积分限幅,防止积分饱和
|
|
float integral =
|
|
integral_prev + I * TIME_SLICE * 0.5f * (error + error_prev);
|
|
integral = _constrain(integral, -limit, limit);
|
|
|
|
// D环(微分环节)
|
|
float derivative = D * (error - error_prev) / TIME_SLICE;
|
|
|
|
// 将P,I,D三环的计算值加起来
|
|
float output = proportional + integral + derivative;
|
|
output = _constrain(output, -limit, limit);
|
|
|
|
// 输出斜坡限制
|
|
// 简化的斜坡限制(单行逻辑)
|
|
if (output_ramp > 0) {
|
|
float max_delta = output_ramp * TIME_SLICE;
|
|
output = output_prev +
|
|
fmaxf(-max_delta, fminf(max_delta, output - output_prev));
|
|
}
|
|
// 保存值(为了下一次循环)
|
|
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;
|
|
} |