Skip to content

Commit b04199c

Browse files
DzikuVxPaweł Spychalski
andauthored
Minor PID controller improvement: use cache millis instead of calling millis() multiple times in the loop. (#11439)
Co-authored-by: Paweł Spychalski <pspychalski@ouotlook.com>
1 parent 69a1352 commit b04199c

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

src/main/flight/pid.c

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,7 @@ static EXTENDED_FASTRAM pidControllerFnPtr pidControllerApplyFn;
170170
static EXTENDED_FASTRAM filterApplyFnPtr dTermLpfFilterApplyFn;
171171
static EXTENDED_FASTRAM bool restartAngleHoldMode = true;
172172
static EXTENDED_FASTRAM bool angleHoldIsLevel = false;
173+
static EXTENDED_FASTRAM timeMs_t pidLoopNowMs;
173174

174175
#define FIXED_WING_LEVEL_TRIM_MAX_ANGLE 10.0f // Max angle auto trimming can demand
175176
#define FIXED_WING_LEVEL_TRIM_DIVIDER 50.0f
@@ -820,7 +821,7 @@ static void iTermLockApply(pidState_t *pidState, const float rateTarget, const f
820821

821822
//When abs of rate target is above 20% of max rate, we start tracking time
822823
if (fabsf(rateTarget) > maxRate * 0.2f) {
823-
pidState->attenuation.targetOverThresholdTimeMs = millis();
824+
pidState->attenuation.targetOverThresholdTimeMs = pidLoopNowMs;
824825
}
825826

826827
//If error is below threshold, we no longer track time for lock mechanism
@@ -833,7 +834,7 @@ static void iTermLockApply(pidState_t *pidState, const float rateTarget, const f
833834
* - dampingFactor
834835
* - for 500ms (fw_iterm_lock_time_max_ms) force 0 if error is above threshold
835836
*/
836-
pidState->attenuation.aI = MIN(dampingFactor, (errorThresholdReached && (millis() - pidState->attenuation.targetOverThresholdTimeMs) < pidProfile()->fwItermLockTimeMaxMs) ? 0.0f : 1.0f);
837+
pidState->attenuation.aI = MIN(dampingFactor, (errorThresholdReached && (pidLoopNowMs - pidState->attenuation.targetOverThresholdTimeMs) < pidProfile()->fwItermLockTimeMaxMs) ? 0.0f : 1.0f);
837838

838839
//P & D damping factors are always the same and based on current damping factor
839840
pidState->attenuation.aP = dampingFactor;
@@ -1222,6 +1223,7 @@ void updateAngleHold(float *angleTarget, uint8_t axis)
12221223
void FAST_CODE pidController(float dT)
12231224
{
12241225
const float dT_inv = 1.0f / dT;
1226+
pidLoopNowMs = millis();
12251227

12261228
if (!pidFiltersConfigured) {
12271229
return;

0 commit comments

Comments
 (0)