libstp
Robotics library for Botball
Loading...
Searching...
No Matches
motor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cmath>
4#include <numbers>
5#include <optional>
6#include <stdexcept>
7#include <utility>
8
9namespace libstp::foundation
10{
14 inline constexpr double kDefaultEncoderTicksPerRev = 1440.0;
15
17 struct PidGains
18 {
19 double kp{1.0}, ki{0.0}, kd{0.0};
20 };
21
24 {
25 double kS{0.0};
26 double kV{0.0};
27 double kA{0.0};
28 };
29
32 {
33 double ticks_to_rad{2.0 * std::numbers::pi / kDefaultEncoderTicksPerRev};
34 double vel_lpf_alpha{0.5};
39 double bemf_offset{0.0};
40 std::optional<PidGains> pid{};
45
46 MotorCalibration() = default;
47
49 double vel_lpf_alpha,
50 std::optional<PidGains> pid = std::nullopt,
51 double bemf_offset = 0.0,
52 double static_friction_pct = 0.0)
56 pid(std::move(pid)),
58 {
59 }
60
65 void validate() const
66 {
67 if (!(ticks_to_rad > 0.0))
68 throw std::invalid_argument("MotorCalibration: ticks_to_rad must be > 0");
69 if (!(vel_lpf_alpha >= 0.0 && vel_lpf_alpha <= 1.0))
70 throw std::invalid_argument("MotorCalibration: vel_lpf_alpha must be in [0, 1]");
71 if (!std::isfinite(bemf_offset))
72 throw std::invalid_argument("MotorCalibration: bemf_offset must be finite");
73 if (!(std::isfinite(static_friction_pct) && static_friction_pct >= 0.0))
74 throw std::invalid_argument("MotorCalibration: static_friction_pct must be finite and >= 0");
75 if (pid && (!std::isfinite(pid->kp) || !std::isfinite(pid->ki) || !std::isfinite(pid->kd)))
76 throw std::invalid_argument("MotorCalibration: pid gains must be finite");
77 }
78 };
79
82 {
83 public:
85
86 explicit FeedforwardController(Feedforward ff = {}) : config(ff) {}
87
88 [[nodiscard]] double calculate(double velocity, double acceleration = 0.0) const
89 {
90 double output = config.kV * velocity + config.kA * acceleration;
91 if (velocity != 0.0)
92 {
93 output += config.kS * std::copysign(1.0, velocity);
94 }
95 return output;
96 }
97 };
98}
FeedforwardController(Feedforward ff={})
Definition motor.hpp:86
double calculate(double velocity, double acceleration=0.0) const
Definition motor.hpp:88
constexpr double kDefaultEncoderTicksPerRev
Definition motor.hpp:14
Feedforward terms for velocity and acceleration control.
Definition motor.hpp:24
std::optional< PidGains > pid
Definition motor.hpp:40
MotorCalibration(double ticks_to_rad, double vel_lpf_alpha, std::optional< PidGains > pid=std::nullopt, double bemf_offset=0.0, double static_friction_pct=0.0)
Definition motor.hpp:48
Basic PID gains without integrator and output shaping parameters.
Definition motor.hpp:18