Fang-Robotics-MCB
Fang Robotics Team Codebase
Loading...
Searching...
No Matches
smooth_pid.hpp
Go to the documentation of this file.
1#ifndef FANG_ROBOTICS_MCB_TRAP_SMOOTH_PID_HPP
2#define FANG_ROBOTICS_MCB_TRAP_SMOOTH_PID_HPP
6#include <cmath>
7
10
11namespace trap
12{
13 namespace algorithms
14 {
20 template<typename ErrorType, typename ControlType, typename TimeUnit>
22 {
23 public:
24 //A bit of cheating
26
27 SmoothPid(const Config& config, ErrorType initialLastError = ErrorType{0.0})
28 : m_smoothPid{config}, m_lastError{initialLastError}
29 {
30 }
31
37 ControlType runController(ErrorType error)
38 {
39 const TimeUnit deltaTime{m_runControllerTimer.getDurationAndReset()};
40 return runController(error, deltaTime);
41 }
42
46 ControlType runController(const ErrorType& error, const TimeUnit& deltaTime)
47 {
48 const ErrorType deltaError{error - m_lastError};
49 const double errorDerivative{static_cast<double>(deltaError) / static_cast<double>(deltaTime)};
50 //Prevents oscillations by filtering out higher frequencies
51 const double cleanErrorDerivative{tap::algorithms::lowPassFilter(m_lastDerivative, errorDerivative, k_lowPassAlpha)};
52
53 m_lastDerivative = errorDerivative;
54 m_lastError = error;
55
56 return runController(error, cleanErrorDerivative, deltaTime);
57 }
58
63 ControlType runController(ErrorType error, double errorDerivative, TimeUnit deltaTime)
64 {
65 float result {m_smoothPid.runController(static_cast<float>(error), static_cast<float>(errorDerivative), static_cast<float>(deltaTime))};
66 FANG_ASSERT(!std::isnan(result), "Cannot be nan");
67 static float testResult{};
68 testResult = result;
69 return ControlType{result};
70 }
71
72 private:
73 static constexpr double k_lowPassAlpha{0.0};
75 ErrorType m_lastError{0};
76 double m_lastDerivative{0};
77 fang::chrono::SimpleTimer m_runControllerTimer{};
78 };
79
80 }
81}
82#endif
Definition simple_timer.hpp:12
Microseconds getDurationAndReset()
Definition simple_timer.cpp:20
Definition smooth_pid.hpp:57
virtual float runController(float error, float errorDerivative, float dt)
Definition smooth_pid.cpp:41
Definition smooth_pid.hpp:22
ControlType runController(ErrorType error)
Definition smooth_pid.hpp:37
SmoothPid(const Config &config, ErrorType initialLastError=ErrorType{0.0})
Definition smooth_pid.hpp:27
ControlType runController(const ErrorType &error, const TimeUnit &deltaTime)
Definition smooth_pid.hpp:46
ControlType runController(ErrorType error, double errorDerivative, TimeUnit deltaTime)
Definition smooth_pid.hpp:63
#define FANG_ASSERT(CONDITION, DESC)
Definition fang_assert.hpp:24
Definition pwm_info.hpp:4
float lowPassFilter(float prevValue, float newValue, float alpha)
Definition math_user_utils.hpp:113
Definition dimensional_smooth_pid.hpp:8
Definition smooth_pid.hpp:36