Skip to content

Commit 0fbd0da

Browse files
authored
Merge pull request br3ttb#8 from gnalbandian/patch-2
Please consider this aproach
2 parents 8b465d4 + d7e4e31 commit 0fbd0da

File tree

1 file changed

+32
-22
lines changed

1 file changed

+32
-22
lines changed

examples/AutoTune_Filter_DIRECT/AutoTune_Filter_DIRECT.ino

Lines changed: 32 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -39,30 +39,40 @@ void setup() {
3939

4040
void loop() {
4141

42-
if (_myPID.autoTune->autoTuneLoop() != _myPID.autoTune->RUN_PID) { // running autotune
43-
44-
Input = avg(_myPID.analogReadFast(inputPin)); // filtered input
45-
analogWrite(outputPin, Output);
46-
}
47-
48-
if (_myPID.autoTune->autoTuneLoop() == _myPID.autoTune->NEW_TUNINGS) { // get new tunings
49-
_myPID.autoTune->setAutoTuneConstants(&Kp, &Ki, &Kd); // set new tunings
50-
_myPID.clearAutoTune(); // releases memory used by AutoTune object
51-
_myPID.SetMode(QuickPID::AUTOMATIC); // setup PID
52-
_myPID.SetTunings(Kp, Ki, Kd, POn); // apply new tunings to PID
53-
Setpoint = 500;
54-
}
55-
56-
if (_myPID.autoTune->autoTuneLoop() == _myPID.autoTune->RUN_PID) { // running PID
57-
if (printOrPlotter == 0) { // plotter
58-
Serial.print("Setpoint:"); Serial.print(Setpoint); Serial.print(",");
59-
Serial.print("Input:"); Serial.print(Input); Serial.print(",");
60-
Serial.print("Output:"); Serial.print(Output); Serial.println();
61-
}
62-
Input = _myPID.analogReadFast(inputPin);
42+
if (_myPID.autoTune) // Avoid deferencing nullptr after _myPID.clearAutoTune()
43+
{
44+
uint8_t autoTuningCurrentStage = autoTuneLoop();
45+
if(autoTuningCurrentStage < _myPID.autoTune->RUN_PID)
46+
{
47+
Input = avg(_myPID.analogReadFast(inputPin)); // filtered input
48+
analogWrite(outputPin, Output);
49+
50+
if (autoTuningCurrentStage == _myPID.autoTune->NEW_TUNINGS) // get new tunings
51+
{
52+
_myPID.autoTune->setAutoTuneConstants(&Kp, &Ki, &Kd); // set new tunings
53+
_myPID.SetMode(QuickPID::AUTOMATIC); // setup PID
54+
_myPID.SetTunings(Kp, Ki, Kd, POn); // apply new tunings to PID
55+
Setpoint = 500;
56+
}
57+
}
58+
else // RUN_PID stage
59+
{
60+
if (printOrPlotter == 0) // plotter
61+
{
62+
_myPID.clearAutoTune(); // releases memory used by AutoTune object
63+
Serial.print("Setpoint:"); Serial.print(Setpoint); Serial.print(",");
64+
Serial.print("Input:"); Serial.print(Input); Serial.print(",");
65+
Serial.print("Output:"); Serial.print(Output); Serial.println();
66+
}
67+
}
68+
69+
}
70+
else // Autotune already done (or not created)
71+
{
72+
Input = _myPID.analogReadFast(inputPin);
6373
_myPID.Compute();
6474
analogWrite(outputPin, Output);
65-
}
75+
}
6676
}
6777

6878
float avg(int inputVal) {

0 commit comments

Comments
 (0)