/// @file AC_PID.cpp1/// @brief General-purpose PID controller with input, error, and derivative filtering, plus slew rate limiting and EEPROM gain storage.23#include <AP_Math/AP_Math.h>4#include "AC_PID.h"56#define AC_PID_DEFAULT_NOTCH_ATTENUATION 4078const AP_Param::GroupInfo AC_PID::var_info[] = {9// @Param: P10// @DisplayName: PID Proportional Gain11// @Description: P Gain which produces an output value that is proportional to the current error value12AP_GROUPINFO_FLAGS_DEFAULT_POINTER("P", 0, AC_PID, _kp, default_kp),1314// @Param: I15// @DisplayName: PID Integral Gain16// @Description: I Gain which produces an output that is proportional to both the magnitude and the duration of the error17AP_GROUPINFO_FLAGS_DEFAULT_POINTER("I", 1, AC_PID, _ki, default_ki),1819// @Param: D20// @DisplayName: PID Derivative Gain21// @Description: D Gain which produces an output that is proportional to the rate of change of the error22AP_GROUPINFO_FLAGS_DEFAULT_POINTER("D", 2, AC_PID, _kd, default_kd),2324// 3 was for uint16 IMAX2526// @Param: FF27// @DisplayName: FF FeedForward Gain28// @Description: FF Gain which produces an output value that is proportional to the demanded input29AP_GROUPINFO_FLAGS_DEFAULT_POINTER("FF", 4, AC_PID, _kff, default_kff),3031// @Param: IMAX32// @DisplayName: PID Integral Maximum33// @Description: The maximum/minimum value that the I term can output34AP_GROUPINFO_FLAGS_DEFAULT_POINTER("IMAX", 5, AC_PID, _kimax, default_kimax),3536// 6 was for float FILT3738// 7 is for float ILMI and FF3940// index 8 was for AFF4142// @Param: FLTT43// @DisplayName: PID Target filter frequency in Hz44// @Description: Low-pass filter frequency applied to the target input (Hz)45// @Units: Hz46AP_GROUPINFO_FLAGS_DEFAULT_POINTER("FLTT", 9, AC_PID, _filt_T_hz, default_filt_T_hz),4748// @Param: FLTE49// @DisplayName: PID Error filter frequency in Hz50// @Description: Low-pass filter frequency applied to the error (Hz)51// @Units: Hz52AP_GROUPINFO_FLAGS_DEFAULT_POINTER("FLTE", 10, AC_PID, _filt_E_hz, default_filt_E_hz),5354// @Param: FLTD55// @DisplayName: PID Derivative term filter frequency in Hz56// @Description: Low-pass filter frequency applied to the derivative (Hz)57// @Units: Hz58AP_GROUPINFO_FLAGS_DEFAULT_POINTER("FLTD", 11, AC_PID, _filt_D_hz, default_filt_D_hz),5960// @Param: SMAX61// @DisplayName: Slew rate limit62// @Description: Sets an upper limit on the slew rate produced by the combined P and D gains. If the amplitude of the control action produced by the rate feedback exceeds this value, then the D+P gain is reduced to respect the limit. This limits the amplitude of high frequency oscillations caused by an excessive gain. The limit should be set to no more than 25% of the actuators maximum slew rate to allow for load effects. Note: The gain will not be reduced to less than 10% of the nominal value. A value of zero will disable this feature.63// @Range: 0 20064// @Increment: 0.565// @User: Advanced66AP_GROUPINFO_FLAGS_DEFAULT_POINTER("SMAX", 12, AC_PID, _slew_rate_max, default_slew_rate_max),6768// @Param: PDMX69// @DisplayName: PD sum maximum70// @Description: The maximum/minimum value that the sum of the P and D term can output71// @User: Advanced72AP_GROUPINFO("PDMX", 13, AC_PID, _kpdmax, 0),7374// @Param: D_FF75// @DisplayName: PID Derivative FeedForward Gain76// @Description: FF D Gain which produces an output that is proportional to the rate of change of the target77// @Range: 0 0.0278// @Increment: 0.000179// @User: Advanced80AP_GROUPINFO_FLAGS_DEFAULT_POINTER("D_FF", 14, AC_PID, _kdff, default_kdff),8182#if AP_FILTER_ENABLED83// @Param: NTF84// @DisplayName: PID Target notch filter index85// @Description: PID Target notch filter index86// @Range: 1 887// @User: Advanced88AP_GROUPINFO("NTF", 15, AC_PID, _notch_T_filter, 0),8990// @Param: NEF91// @DisplayName: PID Error notch filter index92// @Description: PID Error notch filter index93// @Range: 1 894// @User: Advanced95AP_GROUPINFO("NEF", 16, AC_PID, _notch_E_filter, 0),96#endif9798AP_GROUPEND99};100101// Constructor102AC_PID::AC_PID(float initial_p, float initial_i, float initial_d, float initial_ff, float initial_imax, float initial_filt_T_hz, float initial_filt_E_hz, float initial_filt_D_hz,103float initial_srmax, float initial_srtau, float initial_dff) :104default_kp(initial_p),105default_ki(initial_i),106default_kd(initial_d),107default_kff(initial_ff),108default_kdff(initial_dff),109default_kimax(initial_imax),110default_filt_T_hz(initial_filt_T_hz),111default_filt_E_hz(initial_filt_E_hz),112default_filt_D_hz(initial_filt_D_hz),113default_slew_rate_max(initial_srmax)114{115// load parameter values from eeprom116AP_Param::setup_object_defaults(this, var_info);117118// this param is not in the table, so its default is no loaded in the call above119_slew_rate_tau.set(initial_srtau);120121// reset input filter to first value received122_flags._reset_filter = true;123124memset(&_pid_info, 0, sizeof(_pid_info));125126// slew limit scaler allows for plane to use degrees/sec slew127// limit128_slew_limit_scale = 1;129}130131// Sets the target low-pass filter frequency (Hz)132void AC_PID::set_filt_T_hz(float hz)133{134_filt_T_hz.set(fabsf(hz));135}136137// Sets the error low-pass filter frequency (Hz)138void AC_PID::set_filt_E_hz(float hz)139{140_filt_E_hz.set(fabsf(hz));141}142143// Sets the derivative low-pass filter frequency (Hz)144void AC_PID::set_filt_D_hz(float hz)145{146_filt_D_hz.set(fabsf(hz));147}148149// slew_limit - set slew limit150void AC_PID::set_slew_limit(float smax)151{152_slew_rate_max.set(fabsf(smax));153}154155// Configures optional notch filters for target and error signals using the given sample rate.156// Filters are dynamically allocated and validated via the AP_Filter API.157void AC_PID::set_notch_sample_rate(float sample_rate)158{159#if AP_FILTER_ENABLED160if (_notch_T_filter == 0 && _notch_E_filter == 0) {161return;162}163164if (_notch_T_filter != 0) {165if (_target_notch == nullptr) {166_target_notch = NEW_NOTHROW NotchFilterFloat();167}168// Lookup filter definition and initialize if valid169AP_Filter* filter = AP::filters().get_filter(_notch_T_filter);170if (filter != nullptr && !filter->setup_notch_filter(*_target_notch, sample_rate)) {171delete _target_notch;172_target_notch = nullptr;173_notch_T_filter.set(0); // disable filter if setup fails174}175}176177if (_notch_E_filter != 0) {178if (_error_notch == nullptr) {179_error_notch = NEW_NOTHROW NotchFilterFloat();180}181// Lookup filter definition and initialize if valid182AP_Filter* filter = AP::filters().get_filter(_notch_E_filter);183if (filter != nullptr && !filter->setup_notch_filter(*_error_notch, sample_rate)) {184delete _error_notch;185_error_notch = nullptr;186_notch_E_filter.set(0); // disable filter if setup fails187}188}189#endif190}191192// Computes the PID output using a target and measurement input.193// Applies filters to the target and error, calculates the derivative and updates the integrator.194// If `limit` is true, the integrator is allowed to shrink but not grow.195float AC_PID::update_all(float target, float measurement, float dt, bool limit, float pd_scale, float i_scale)196{197// Return zero if input is invalid (NaN or infinite)198if (!isfinite(target) || !isfinite(measurement)) {199return 0.0f;200}201202// Flag used for logging to indicate a filter reset occurred203_pid_info.reset = _flags._reset_filter;204// Reset filters to match the current input (first sample or after reset)205if (_flags._reset_filter) {206// Reset filters to match the current inputs207_flags._reset_filter = false;208209// Reset target filter210_target = target;211#if AP_FILTER_ENABLED212if (_target_notch != nullptr) {213_target_notch->reset();214_target = _target_notch->apply(_target);215}216#endif217218// Calculate error and reset error filter219_error = _target - measurement;220#if AP_FILTER_ENABLED221if (_error_notch != nullptr) {222_error_notch->reset();223_error = _error_notch->apply(_error);224}225#endif226// Clear derivative history to avoid spikes after reset227_derivative = 0.0f;228_target_derivative = 0.0f;229230} else {231232// Apply target filters233const float target_last = _target;234#if AP_FILTER_ENABLED235if (_target_notch != nullptr) {236// Allocate and set up target notch filter237target = _target_notch->apply(target);238}239#endif240// Apply first-order low-pass filter to target value241_target += get_filt_T_alpha(dt) * (target - _target);242243// Calculate error and apply error filter244const float error_last = _error;245float error = _target - measurement;246#if AP_FILTER_ENABLED247if (_error_notch != nullptr) {248// Allocate and set up error notch filter249error = _error_notch->apply(error);250}251#endif252// apply notch filters before FTLD/FLTE to minimize shot noise253_error += get_filt_E_alpha(dt) * (error - _error);254255if (is_positive(dt)) {256// Compute and low-pass filter the error derivative (D term)257float derivative = (_error - error_last) / dt;258_derivative += get_filt_D_alpha(dt) * (derivative - _derivative);259// Calculate target derivative for D_FF contribution260_target_derivative = (_target - target_last) / dt;261}262}263264// Integrate error (with wind-up protection if limit is active)265// If limit is active, allow I-term to shrink but not grow266update_i(dt, limit, i_scale);267268float P_out = (_error * _kp);269float D_out = (_derivative * _kd);270float I_out = _integrator;271272// Calculate dynamic modifier to reduce P+D output based on slew rate limiter273_pid_info.Dmod = _slew_limiter.modifier((_pid_info.P + _pid_info.D) * _slew_limit_scale, dt);274_pid_info.slew_rate = _slew_limiter.get_slew_rate();275276// This modifier is used to reduce control effort under fast transients277P_out *= _pid_info.Dmod;278D_out *= _pid_info.Dmod;279280// scale pd output if required281P_out *= pd_scale;282D_out *= pd_scale;283284_pid_info.PD_limit = false;285// Apply PD sum limit if enabled286if (is_positive(_kpdmax)) {287const float PD_sum_abs = fabsf(P_out + D_out);288if (PD_sum_abs > _kpdmax) {289const float pd_limit_scale = _kpdmax / PD_sum_abs;290P_out *= pd_limit_scale;291D_out *= pd_limit_scale;292_pid_info.PD_limit = true;293}294}295296_pid_info.target = _target;297_pid_info.actual = measurement;298_pid_info.error = _error;299_pid_info.P = P_out;300_pid_info.D = D_out;301_pid_info.I = I_out;302_pid_info.limit = limit;303// Set I set flag for logging and clear304_pid_info.I_term_set = _flags._I_set;305_flags._I_set = false;306_pid_info.FF = _target * _kff;307_pid_info.DFF = _target_derivative * _kdff;308309return P_out + D_out + I_out;310}311312// Computes the PID output from an error input only (target assumed to be zero).313// Applies error filtering and updates the derivative and integrator.314// Target and measurement must be set separately for logging.315// todo: remove function when it is no longer used.316float AC_PID::update_error(float error, float dt, bool limit)317{318// don't process inf or NaN319if (!isfinite(error)) {320return 0.0f;321}322323// Reuse update all code path, zero target and pass negative error as measurement324// Pass negative error as "measurement" so that error = target - measurement evaluates correctly325// Bypasses target filtering for legacy compatibility326_target = 0.0;327const float output = update_all(0.0, -error, dt, limit);328329// Make sure logged target and actual are still 0 to maintain behaviour330_pid_info.target = 0.0;331_pid_info.actual = 0.0;332333return output;334}335336// Updates the integrator based on current error and dt.337// If `limit` is true, the integrator is only allowed to shrink to avoid wind-up.338// i_scale can be used to temporarily scale the updated I-term, by default is 1 - should not be set to 0339void AC_PID::update_i(float dt, bool limit, float i_scale)340{341if (!is_zero(_ki) && is_positive(dt)) {342// Allow integrator growth only if not limited, or if error opposes the integrator direction343if (!limit || ((is_positive(_integrator) && is_negative(_error)) || (is_negative(_integrator) && is_positive(_error)))) {344_integrator += ((float)_error * _ki) * i_scale * dt;345_integrator = constrain_float(_integrator, -_kimax, _kimax);346}347} else {348_integrator = 0.0f;349}350}351352float AC_PID::get_p() const353{354return _pid_info.P;355}356357float AC_PID::get_i() const358{359return _integrator;360}361362float AC_PID::get_d() const363{364return _pid_info.D;365}366367float AC_PID::get_ff() const368{369return _pid_info.FF + _pid_info.DFF;370}371372float AC_PID::get_ff_component() const373{374return _pid_info.FF;375}376377float AC_PID::get_dff_component() const378{379return _pid_info.DFF;380}381382// Used to fully zero the I term between mode changes or initialization383void AC_PID::reset_I()384{385_flags._I_set = true;386_integrator = 0.0;387}388389// Loads controller configuration from EEPROM, including gains and filter frequencies. (not used)390void AC_PID::load_gains()391{392_kp.load();393_ki.load();394_kd.load();395_kff.load();396_filt_T_hz.load();397_filt_E_hz.load();398_filt_D_hz.load();399}400401// Saves controller configuration from EEPROM, including gains and filter frequencies. Used by autotune to save gains before tuning.402void AC_PID::save_gains()403{404_kp.save();405_ki.save();406_kd.save();407_kff.save();408_filt_T_hz.save();409_filt_E_hz.save();410_filt_D_hz.save();411}412413// Returns alpha value for the target low-pass filter (based on filter frequency and dt)414float AC_PID::get_filt_T_alpha(float dt) const415{416return calc_lowpass_alpha_dt(dt, _filt_T_hz);417}418419// Returns alpha value for the error low-pass filter (based on filter frequency and dt)420float AC_PID::get_filt_E_alpha(float dt) const421{422return calc_lowpass_alpha_dt(dt, _filt_E_hz);423}424425// Returns alpha value for the derivative low-pass filter (based on filter frequency and dt)426float AC_PID::get_filt_D_alpha(float dt) const427{428return calc_lowpass_alpha_dt(dt, _filt_D_hz);429}430431// Sets the integrator directly, clamped to the IMAX bounds. Also flags I-term as externally set.432void AC_PID::set_integrator(float integrator)433{434_flags._I_set = true;435_integrator = constrain_float(integrator, -_kimax, _kimax);436}437438// Gradually adjust the integrator toward a desired value using a time constant.439// Typically used to "relax" the I-term in dynamic conditions.440void AC_PID::relax_integrator(float integrator, float dt, float time_constant)441{442integrator = constrain_float(integrator, -_kimax, _kimax);443if (is_positive(dt)) {444_flags._I_set = true;445_integrator = _integrator + (integrator - _integrator) * (dt / (dt + time_constant));446}447}448449450