vexide_math/pid.rs
1//! PID controllers.
2//!
3//! PID controllers are first created with [`PidController::new`]
4//! and then can be utilized by calling [`PidController::update`] repeatedly.
5
6use core::time::Duration;
7
8/// A proportional–integral–derivative controller.
9///
10/// This controller is used to smoothly move motors to a certain point,
11/// and allows for feedback-based power adjustments. This is desirable
12/// over just setting the motor power, as it can be tuned to make the
13/// motor stop in exactly the right position without overshooting.
14#[derive(Debug, Clone, Copy)]
15pub struct PidController {
16 /// Proportional constant. This is multiplied by the error to get the
17 /// proportional component of the output.
18 pub kp: f32,
19 /// Integral constant. This accounts for the past values of the error.
20 pub ki: f32,
21 /// Derivative constant. This allows you to change the motor behavior
22 /// based on the rate of change of the error (predicting future values).
23 pub kd: f32,
24
25 last_time: vexide_core::time::Instant,
26 last_position: f32,
27 i: f32,
28}
29
30impl PidController {
31 /// Create a new PID controller with the given constants.
32 pub fn new(kp: f32, ki: f32, kd: f32) -> Self {
33 Self {
34 kp,
35 ki,
36 kd,
37 last_time: vexide_core::time::Instant::now(),
38 last_position: 0.0,
39 i: 0.0,
40 }
41 }
42
43 /// Update the PID controller with the current setpoint and position.
44 pub fn update(&mut self, setpoint: f32, position: f32) -> f32 {
45 let mut delta_time = self.last_time.elapsed();
46 if delta_time.is_zero() {
47 delta_time += Duration::from_micros(1);
48 }
49 let error = setpoint - position;
50
51 self.i += error * delta_time.as_secs_f32();
52
53 let p = self.kp * error;
54 let i = self.ki * self.i;
55
56 let mut d = (position - self.last_position) / delta_time.as_secs_f32();
57 if d.is_nan() {
58 d = 0.0
59 }
60
61 let output = p + i + d;
62
63 self.last_position = position;
64 self.last_time = vexide_core::time::Instant::now();
65
66 output
67 }
68}