libpromeki 1.0.0-alpha
PROfessional MEdia toolKIt
 
Loading...
Searching...
No Matches
pidcontroller.h
Go to the documentation of this file.
1
9#pragma once
10
11
12#include <promeki/config.h>
13#if PROMEKI_ENABLE_CORE
14#include <promeki/function.h>
15#include <promeki/namespace.h>
16#include <functional>
17
18PROMEKI_NAMESPACE_BEGIN
19
39template <typename ValueType = double, typename TimeType = double> class PIDController {
40 public:
42 using CurrentTimeFunc = Function<TimeType()>;
44 using CurrentValueFunc = Function<ValueType()>;
45
51 PIDController(CurrentValueFunc currentValueFunc, CurrentTimeFunc currentTimeFunc)
52 : _gainP(1), _gainI(0), _gainD(0), _integral(0), _prevError(0), _setPoint(0),
53 _currentValue(currentValueFunc), _currentTime(currentTimeFunc), _prevUpdate(_currentTime()) {}
54
56 ValueType getGainP() const { return _gainP; }
57
62 void setGainP(const ValueType &val) { _gainP = val; }
63
65 ValueType getGainI() const { return _gainI; }
66
71 void setGainI(const ValueType &val) { _gainI = val; }
72
74 ValueType getGainD() const { return _gainD; }
75
80 void setGainD(const ValueType &val) { _gainD = val; }
81
86 void updateSetPoint(const ValueType &val) { _setPoint = val; }
87
97 ValueType step() {
98 TimeType now = _currentTime();
99 TimeType dt = now - _prevUpdate;
100 _prevUpdate = now;
101
102 ValueType pv = _currentValue();
103 ValueType error = _setPoint - pv;
104 _integral += error * dt;
105 ValueType derivative = (error - _prevError) / dt;
106 _prevError = error;
107
108 return _gainP * error + _gainI * _integral + _gainD * derivative;
109 }
110
112 void reset() {
113 _integral = {};
114 _prevError = {};
115 _prevUpdate = _currentTime();
116 return;
117 }
118
119 private:
120 ValueType _gainP = 1;
121 ValueType _gainI = 1;
122 ValueType _gainD = 1;
123 ValueType _integral = 0;
124 ValueType _prevError = 0;
125 ValueType _setPoint = 0;
126 CurrentValueFunc _currentValue;
127 CurrentTimeFunc _currentTime;
128 TimeType _prevUpdate = 0;
129};
130
131
132PROMEKI_NAMESPACE_END
133
134#endif // PROMEKI_ENABLE_CORE