Skip to content

Instantly share code, notes, and snippets.

@hamaluik
Last active November 19, 2015 16:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamaluik/5d2ec42ba145ac69ae64 to your computer and use it in GitHub Desktop.
Save hamaluik/5d2ec42ba145ac69ae64 to your computer and use it in GitHub Desktop.
class PID
{
public double KP { get; set; }
public double KI { get; set; }
public double KD { get; set; }
public double SetPoint { get; set; }
public double MinSet { get; set; }
public double MaxSet { get; set; }
private DateTime lastTime;
private double iTerm = 0;
private double lastPV = 0;
public PID(double minSet, double maxSet)
{
KP = 5;
KI = 0;
KD = 0;
MinSet = minSet;
MaxSet = maxSet;
}
public double UpdateController(double processValue)
{
DateTime now = DateTime.Now;
double error = SetPoint - processValue;
double pTerm = KP * error;
double dTerm = 0;
// if we have a previous time to calculate the integral
// and derivative terms, do so
if(lastTime != null)
{
// calculate the time difference
double dt = (now - lastTime).TotalSeconds;
// calculate the integral component
iTerm += KI * error * dt;
// calculate the derivative component
// NOTE: use -ΔPV instead of ΔErr to eliminiate derivative kick
dTerm = -KD * (processValue - lastPV) / dt;
lastPV = processValue;
}
lastTime = now;
// deal with integral windup
// and clamp it to [MinSet, MaxSet]
double result = pTerm + iTerm + dTerm;
if(result > MaxSet) {
iTerm -= result - MaxSet;
result = MaxSet;
}
else if(result < MinSet) {
iTerm += MinSet - result;
result = MinSet;
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment