Skip to content

Update PIDController.cpp #21

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions src/PIDController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,10 @@ PIDController::PIDController () {
void PIDController::begin () {
Kp = 1;
Ki = 1;
aKi = 1;
Kd = 1;
divisor = 10;
aKiDivisor = 1000;
doLimit = false;
init = true;
}
Expand Down Expand Up @@ -64,6 +66,11 @@ void PIDController::minimize (double newMinimize) {
divisor = newMinimize;
}

void PIDController::adaptiveRetune (double newFactor) {
aKiDivisor = newValue;
doAdaption = true;
}

// Getters
double PIDController::getOutput () {
return output;
Expand All @@ -78,19 +85,28 @@ double PIDController::compute (double sensor, String graph, String verbose) {
if (!init) return 0;

// Calculate time difference since last time executed
unsigned long now = millis();
unsigned long now = micros();
double timeChange = (double)(now - lastTime);

// Failsafe, return unchanged to prevent divide by 0 what results in NaN
if (timeChange < 1.0) return output;

// Calculate error (P, I and D)
double error = setPoint - sensor;
error = setPoint - sensor;

// Calculate adaptive Ki
if (doAdaption) {
aKi = setPoint / aKiDivisor;
}

errSum += error * timeChange;
if (doLimit) {
errSum = constrain(errSum, minOut * 1.1, maxOut * 1.1);
}
double dErr = (error - lastErr) / timeChange;
dErr = (error - lastErr) / timeChange;

// Calculate the new output by adding all three elements together
double newOutput = (Kp * error + Ki * errSum + Kd * dErr) / divisor;
double newOutput = (Kp * error + Ki * aKi * errSum + Kd * dErr) / divisor;

// If limit is specifyed, limit the output
if (doLimit) {
Expand Down