2015-02-12 14:51:36 -07:00
|
|
|
/*
|
|
|
|
* pid.cpp
|
|
|
|
*/
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
#include "PID.h"
|
2015-02-12 14:51:36 -07:00
|
|
|
#include <ctime>
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
PID::PID( double p, double i, double d )
|
2015-02-12 14:51:36 -07:00
|
|
|
{
|
|
|
|
pGain = p;
|
|
|
|
iGain = i;
|
|
|
|
dGain = d;
|
|
|
|
|
|
|
|
lastPosition = 0;
|
|
|
|
integral = 0;
|
|
|
|
|
|
|
|
lastUpdate = clock();
|
|
|
|
}
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
double PID::update( double current, double desired )
|
2015-02-12 14:51:36 -07:00
|
|
|
{
|
|
|
|
double pAdjust, iAdjust, dAdjust;
|
|
|
|
double difference;
|
|
|
|
double posChange;
|
|
|
|
clock_t newTime;
|
2015-02-21 19:02:33 -07:00
|
|
|
clock_t deltaT;
|
2015-02-12 14:51:36 -07:00
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
newTime = clock();
|
|
|
|
deltaT = newTime - lastUpdate;
|
2015-02-12 14:51:36 -07:00
|
|
|
difference = desired - current;
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
// Porportional
|
2015-02-12 14:51:36 -07:00
|
|
|
pAdjust = pGain * difference;
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
// Integral
|
|
|
|
integral += difference * deltaT;
|
2015-02-12 14:51:36 -07:00
|
|
|
iAdjust = -iGain * integral;
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
// Differential
|
2015-02-12 14:51:36 -07:00
|
|
|
posChange = current - lastPosition;
|
2015-02-21 19:02:33 -07:00
|
|
|
dAdjust = -dGain * posChange / deltaT ;
|
2015-02-12 14:51:36 -07:00
|
|
|
|
|
|
|
|
2015-02-21 19:02:33 -07:00
|
|
|
return (1 + pAdjust) * (1 + iAdjust) * (1 + dAdjust) - 1;
|
2015-02-12 14:51:36 -07:00
|
|
|
}
|
|
|
|
|