From 44eeb07dda46650374f5e634e63035db5891077f Mon Sep 17 00:00:00 2001 From: alevar Date: Wed, 24 Aug 2016 01:28:20 +0300 Subject: [PATCH] Overloaded Compute function to allow setpoint to be specified by the user --- PID_v1.cpp | 34 ++++++++++++++++++++++++++++++++++ PID_v1.h | 5 +++++ 2 files changed, 39 insertions(+) diff --git a/PID_v1.cpp b/PID_v1.cpp index 09b9261..d194143 100644 --- a/PID_v1.cpp +++ b/PID_v1.cpp @@ -74,6 +74,40 @@ bool PID::Compute() else return false; } +/* Compute(double* newSetpoint) **************************************************** + * Same as the Compute() function, but takes a different setpoint as a parameter. + * This allows for user defined alterations to the direction of the PID controller + **********************************************************************************/ + +bool PID::Compute(double* newSetpoint) +{ + if(!inAuto) return false; + unsigned long now = millis(); + unsigned long timeChange = (now - lastTime); + if(timeChange>=SampleTime) + { + /*Compute all the working error variables*/ + float input = *myInput; + float error = *newSetpoint - input; + ITerm+= (ki * error); + if(ITerm > outMax) ITerm= outMax; + else if(ITerm < outMin) ITerm= outMin; + float dInput = (input - lastInput); + + /*Compute PID Output*/ + float output = kp * error + ITerm- kd * dInput; + + if(output > outMax) output = outMax; + else if(output < outMin) output = outMin; + *myOutput = output; + + /*Remember some variables for next time*/ + lastInput = input; + lastTime = now; + return true; + } + else return false; +} /* SetTunings(...)************************************************************* * This function allows the controller's dynamic performance to be adjusted. diff --git a/PID_v1.h b/PID_v1.h index 77b3e4b..17f60b0 100644 --- a/PID_v1.h +++ b/PID_v1.h @@ -24,6 +24,11 @@ class PID // called every time loop() cycles. ON/OFF and // calculation frequency can be set using SetMode // SetSampleTime respectively + + bool Compute(double*) // * performs the PID calculation with a specified setPoint passed as a parameter + // it should be called every time loop() cycles. ON/OFF and + // calculation frequency can be set using SetMode + // SetSampleTime respectively void SetOutputLimits(double, double); //clamps the output to a specific range. 0-255 by default, but //it's likely the user will want to change this depending on