Simple PID controller class with output clamp
Revision 2:994ed695c8a5, committed 2019-02-20
- Comitter:
- Clarkk
- Date:
- Wed Feb 20 22:15:52 2019 +0000
- Parent:
- 1:946d71f8afc6
- Commit message:
- Added variables initialization
Changed in this revision
PIDcontroller.cpp | Show annotated file Show diff for this revision Revisions of this file |
PIDcontroller.h | Show annotated file Show diff for this revision Revisions of this file |
--- a/PIDcontroller.cpp Wed Jul 05 20:30:07 2017 +0000 +++ b/PIDcontroller.cpp Wed Feb 20 22:15:52 2019 +0000 @@ -49,11 +49,39 @@ float PID::processNewValue(float input) { float dt; - error = input - target; - dt = t.read(); - t.reset(); - integral = integral + error*dt; - derivative = (error - previous_error)/dt; + error = target - input; + + if(kp != 0) + pout = kp*error; + else + pout = 0; + // TODO: see if there is a need of a clamp on integral term + if((ki!= 0) || (kd != 0)) + { + dt = t.read(); + t.reset(); + + if(ki != 0) + { + integral = integral + error*dt; + iout = ki*integral; + } + else + iout = 0; + + if(kd != 0) + { + derivative = (error - previous_error)/dt; + dout = kd*derivative; + } + else + dout = 0; + } + else + { + iout = 0; + dout = 0; + } previous_error = error; return getControllerOutput(); @@ -63,7 +91,7 @@ { float output; - output = kp*error + ki*integral + kd*derivative; + output = pout + iout + dout; if(output > outputMax) return outputMax; @@ -73,3 +101,8 @@ return output; } + +float PID::getIntegralTerm(void) +{ + return integral; +}
--- a/PIDcontroller.h Wed Jul 05 20:30:07 2017 +0000 +++ b/PIDcontroller.h Wed Feb 20 22:15:52 2019 +0000 @@ -14,11 +14,13 @@ void setOutputLimits(float min, float max); float processNewValue(float input); float getControllerOutput(void); + float getIntegralTerm(void); private: float target; float kp, ki, kd; + float pout,iout,dout; float integral, derivative; float error, previous_error; float outputMin, outputMax;