Created
November 4, 2023 16:42
-
-
Save ecmjohnson/9fe23b6dd661ef6f0dbfd6eec94aa58f to your computer and use it in GitHub Desktop.
Single header PID controller implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
template<typename T> | |
class PID { | |
public: | |
PID(T Kp, T Ki, T Kd, T minInt, T maxInt) { | |
_kp = Kp; | |
_ki = Ki; | |
_kd = Kd; | |
_minInt = minInt; | |
_maxInt = maxInt; | |
} | |
T computeControl(T error) { | |
// Proportional | |
T pTerm = _kp * error; | |
// Integral | |
_int += error; | |
if (_int < _minInt) | |
_int = _minInt; | |
else if (_int > _maxInt) | |
_int = _maxInt; | |
T iTerm = _ki * _int; | |
// Derivative | |
T dTerm = _kd * (_der - error); | |
_der = error; | |
// Return sum of terms | |
return (pTerm + iTerm + dTerm); | |
} | |
private: | |
// Configuration of controller | |
T _kp {}; | |
T _ki {}; | |
T _kd {}; | |
T _minInt {}; | |
T _maxInt {}; | |
// Internal state | |
T _int {}; | |
T _der {}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment