Skip to content

Instantly share code, notes, and snippets.

@ecmjohnson
Created November 4, 2023 16:42
Show Gist options
  • Save ecmjohnson/9fe23b6dd661ef6f0dbfd6eec94aa58f to your computer and use it in GitHub Desktop.
Save ecmjohnson/9fe23b6dd661ef6f0dbfd6eec94aa58f to your computer and use it in GitHub Desktop.
Single header PID controller implementation
#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