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

96 lines
1.9 KiB
C++
Raw Normal View History

2015-07-10 06:01:56 -07:00
/**
* @file pid.cpp
*
* http://en.wikipedia.org/wiki/PID_controller
*
* @date Sep 16, 2014
2015-12-31 13:02:30 -08:00
* @author Andrey Belomutskiy, (c) 2012-2016
2015-07-10 06:01:56 -07:00
*/
#include "pid.h"
2016-02-06 09:02:24 -08:00
#include "math.h"
Pid::Pid() {
init(NULL, NAN, NAN);
}
2015-07-10 06:01:56 -07:00
2016-01-20 20:03:03 -08:00
Pid::Pid(pid_s *pid, float minResult, float maxResult) {
2016-02-06 09:02:24 -08:00
init(pid, minResult, maxResult);
}
void Pid::init(pid_s *pid, float minResult, float maxResult) {
2016-01-20 20:03:03 -08:00
this->pid = pid;
2015-07-10 06:01:56 -07:00
this->minResult = minResult;
this->maxResult = maxResult;
iTerm = 0;
prevError = 0;
}
float Pid::getValue(float target, float input, float dTime) {
float error = target - input;
2016-01-20 20:03:03 -08:00
float pTerm = pid->pFactor * error;
iTerm += pid->iFactor * dTime * error;
float dTerm = pid->dFactor / dTime * (error - prevError);
2015-07-10 06:01:56 -07:00
prevError = error;
2016-02-06 13:02:41 -08:00
float result = pTerm + iTerm + dTerm + pid->offset;
2015-07-10 06:01:56 -07:00
if (result > maxResult) {
// iTerm -= result - maxResult;
result = maxResult;
} else if (result < minResult) {
// iTerm += minResult - result;
result = minResult;
}
return result;
}
void Pid::updateFactors(float pFactor, float iFactor, float dFactor) {
2016-01-20 20:03:03 -08:00
pid->pFactor = pFactor;
pid->iFactor = iFactor;
pid->dFactor = dFactor;
2015-07-10 06:01:56 -07:00
reset();
}
void Pid::reset(void) {
iTerm = 0;
prevError = 0;
}
float Pid::getP(void) {
2016-01-20 20:03:03 -08:00
return pid->pFactor;
2015-07-10 06:01:56 -07:00
}
float Pid::getI(void) {
2016-01-20 20:03:03 -08:00
return pid->iFactor;
2015-07-10 06:01:56 -07:00
}
2016-01-24 13:01:28 -08:00
float Pid::getPrevError(void) {
return prevError;
}
2015-07-10 06:01:56 -07:00
float Pid::getIntegration(void) {
return iTerm;
}
float Pid::getD(void) {
2016-01-20 20:03:03 -08:00
return pid->dFactor;
2015-07-10 06:01:56 -07:00
}
2016-02-06 09:02:24 -08:00
float Pid::getOffset(void) {
return pid->offset;
}
2015-07-10 06:01:56 -07:00
2016-02-06 09:02:24 -08:00
#if EFI_PROD_CODE || EFI_SIMULATOR
void Pid::postState(TunerStudioOutputChannels *tsOutputChannels) {
tsOutputChannels->debugFloatField2 = getIntegration();
tsOutputChannels->debugFloatField3 = getPrevError();
tsOutputChannels->debugFloatField4 = getI();
tsOutputChannels->debugFloatField5 = getD();
tsOutputChannels->debugIntField1 = getP();
tsOutputChannels->debugIntField2 = getOffset();
}
#endif