流程
代码
限制速度加速度的PID控制
#include <algorithm>
#include <cmath>
#include <chrono>
#include <ros/time.h>
#include "Configure.hpp"
// todo 自动计算dt
class PIDController
{
public:
void init(double kpIn, double kiIn, double kdIn, double maxVIn, double maxAIn);
double calculate(double setpoint, double current, double currentV);
private:
bool initialized = false;
double kp;
double ki;
double kd;
double maxV;
double maxA;
double prevError;
double integral;
double prevTime;
};
#define RATE 10.0
void PIDController::init(double kpIn, double kiIn, double kdIn, double maxVIn, double maxAIn)
{
= kpIn;
kp = kiIn;
ki = kdIn;
kd = maxVIn;
maxV = maxAIn;
maxA = 0;
prevError = 0;
integral = true;
initialized = ros::Time::now().toSec() - 1.0 / RATE;
prevTime }
double PIDController::calculate(double setpoint, double current, double currentV)
{
if (!initialized) {
std::abort();
}
double dt = ros::Time::now().toSec() - prevTime;
= ros::Time::now().toSec();
prevTime
double error = setpoint - current;
+= error * dt;
integral double derivative = (error - prevError) / dt;
= error;
prevError double output = kp * error + ki * integral + kd * derivative;
// 限制最大速度
if (std::abs(output) > maxV) {
= std::copysign(maxV, output);
output }
// 限制最大加速度
else if (std::abs(output - currentV) / dt > maxA) {
= currentV + std::copysign(maxA * dt, output - currentV);
output }
return output;
}