fome-fw/firmware/controllers/math/pid.cpp

56 lines
1.1 KiB
C++
Raw Normal View History

2014-09-15 22:03:07 -07:00
/**
* @file pid.cpp
*
* http://en.wikipedia.org/wiki/PID_controller
*
* @date Sep 16, 2014
* @author Andrey Belomutskiy, (c) 2012-2014
*/
#include "pid.h"
2014-09-16 14:03:03 -07:00
Pid::Pid(float pFactor, float iFactor, float dFactor, float minResult, float maxResult) {
2014-09-15 22:03:07 -07:00
this->pFactor = pFactor;
this->iFactor = iFactor;
this->dFactor = dFactor;
2014-09-16 14:03:03 -07:00
this->minResult = minResult;
this->maxResult = maxResult;
2014-09-15 23:02:58 -07:00
integration = 0;
prevError = 0;
2014-09-15 22:03:07 -07:00
}
2014-09-15 23:02:58 -07:00
float Pid::getValue(float target, float input, float dTime) {
float error = target - input;
float pTerm = pFactor * error;
integration += iFactor * dTime * error;
float dTerm = dFactor / dTime * (error - prevError);
prevError = error;
2014-09-16 14:03:03 -07:00
float result = pTerm + integration + dTerm;
if (result > maxResult) {
integration -= result - maxResult;
result = maxResult;
} else if (result < minResult) {
integration += minResult - result;
result = minResult;
}
return result;
2014-09-15 22:03:07 -07:00
}
2014-12-31 21:04:10 -08:00
void Pid::updateFactors(float pFactor, float iFactor, float dFactor) {
this->pFactor = pFactor;
this->iFactor = iFactor;
this->dFactor = dFactor;
reset();
}
void Pid::reset(void) {
integration = 0;
prevError = 0;
}