-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPID.cpp
43 lines (36 loc) · 1.01 KB
/
PID.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdexcept>
#include "PID.h"
PIDController::PIDController (double target, float kP, float kI, float kD, float dt)
{
if (dt == 0) {
throw std::invalid_argument("timeDelta interval is set to 0");
}
accumulatedError = 0;
previousError = 0;
targetCondition = target;
proportionalGain = kP;
integralGain = kI;
derivativeGain = kD;
timeDelta = dt;
}
double PIDController::_GetProportionalError(double e)
{
return proportionalGain * e;
}
double PIDController::_GetDerivativeError(double e)
{
return derivativeGain * (e - previousError) / timeDelta;
}
void PIDController::_ComputeAccumulatedError(double e)
{
accumulatedError += e * timeDelta;
}
double PIDController::Compute(double currentCondition)
{
double error = targetCondition - currentCondition;
_ComputeAccumulatedError(error);
double result = _GetProportionalError(error) + integralGain * accumulatedError + _GetDerivativeError(error);
previousError = error;
return result;
}