[add] add app level code
This commit is contained in:
1 parent
a8b7c716f3
commit
dcb33f8a99
34 files changed
+1265
-678
No files matched your search
@@ -0,0 +1,55 @@
|
||||
#include "pid.h"
|
||||
#include <string.h>
|
||||
|
||||
void PIDController_Init(PIDController_t *pid)
|
||||
{
|
||||
if (!pid) return;
|
||||
pid->Kp = 0.0f;
|
||||
pid->Ki = 0.0f;
|
||||
pid->Kd = 0.0f;
|
||||
pid->integral = 0.0f;
|
||||
pid->prev_error = 0.0f;
|
||||
pid->output_max = 204800.0f; // 电机最大速度 (0.01 DPS)
|
||||
}
|
||||
|
||||
float PIDController_Compute(PIDController_t *pid, float target, float actual)
|
||||
{
|
||||
if (!pid) return 0.0f;
|
||||
|
||||
float error = target - actual;
|
||||
|
||||
// 比例项
|
||||
float p_term = pid->Kp * error;
|
||||
|
||||
// 积分项 (带抗饱和)
|
||||
pid->integral += error;
|
||||
if (pid->integral > pid->output_max) {
|
||||
pid->integral = pid->output_max;
|
||||
} else if (pid->integral < -pid->output_max) {
|
||||
pid->integral = -pid->output_max;
|
||||
}
|
||||
float i_term = pid->Ki * pid->integral;
|
||||
|
||||
// 微分项
|
||||
float derivative = error - pid->prev_error;
|
||||
float d_term = pid->Kd * derivative;
|
||||
pid->prev_error = error;
|
||||
|
||||
float output = p_term + i_term + d_term;
|
||||
|
||||
// 输出限幅
|
||||
if (output > pid->output_max) {
|
||||
output = pid->output_max;
|
||||
} else if (output < -pid->output_max) {
|
||||
output = -pid->output_max;
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
void PIDController_Reset(PIDController_t *pid)
|
||||
{
|
||||
if (!pid) return;
|
||||
pid->integral = 0.0f;
|
||||
pid->prev_error = 0.0f;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#ifndef __PID_H__
|
||||
#define __PID_H__
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
float Kp, Ki, Kd;
|
||||
float integral;
|
||||
float prev_error;
|
||||
float output_max;
|
||||
} PIDController_t;
|
||||
|
||||
void PIDController_Init(PIDController_t *pid);
|
||||
float PIDController_Compute(PIDController_t *pid, float target, float actual);
|
||||
void PIDController_Reset(PIDController_t *pid);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user