usage/
usage.rs

1use pid_ctrl;
2use num_traits;
3
4fn main() {
5    let mut pid = pid_ctrl::PidCtrl::new_with_pid(3.0, 2.0, 1.0);
6
7    let setpoint = 5.0;
8    let prev_measurement = 0.0;
9    // calling init optional. Setpoint and prev_measurement set to 0.0 by default.
10    // Recommended to avoid derivative kick on startup
11    pid.init(setpoint, prev_measurement);
12
13    let measurement = 0.0;
14    let time_delta = 1.0;
15    assert_eq!(
16        pid.step(pid_ctrl::PidIn::new(measurement, time_delta)), 
17        pid_ctrl::PidOut::new(15.0, 10.0, 0.0, 25.0)
18    );
19
20    // changing pid constants
21    pid.kp.set_scale(4.0);
22    assert_eq!(
23        pid.step(pid_ctrl::PidIn::new(measurement, time_delta)), 
24        pid_ctrl::PidOut::new(20.0, 20.0, 0.0, 40.0)
25    );
26
27    // setting symmetrical limits around zero
28    pid.kp.limits.set_limit(10.0);
29    assert_eq!(
30        pid.step(pid_ctrl::PidIn::new(measurement, time_delta)), 
31        pid_ctrl::PidOut::new(10.0, 30.0, 0.0, 40.0)
32    );
33
34    let time_delta = 0.5;
35    assert_eq!(
36        pid.step(pid_ctrl::PidIn::new(measurement, time_delta)), 
37        pid_ctrl::PidOut::new(10.0, 35.0, 0.0, 45.0)
38    );
39
40    // setting upper limits returns error if new value conflicts with lower limit
41    pid.ki.limits.try_set_upper(28.0).unwrap();  
42    assert_eq!(
43        pid.step(pid_ctrl::PidIn::new(measurement, time_delta)), 
44        pid_ctrl::PidOut::new(10.0, 28.0, 0.0, 38.0)
45    );
46
47    // time_delta gets clamped to Float::epsilon() - Float::infinity()
48    let measurement = 1.0;
49    let time_delta = -7.0;
50    pid.kd.set_scale(num_traits::float::FloatCore::epsilon());
51    assert_eq!(pid.step(
52        pid_ctrl::PidIn::new(measurement, time_delta)), 
53        pid_ctrl::PidOut::new(10.0, 28.0, -1.0, 37.0)
54    );
55
56    // configure setpoint directly
57    pid.setpoint = 1.0;
58    assert_eq!(pid.step(
59        pid_ctrl::PidIn::new(measurement, time_delta)), 
60        pid_ctrl::PidOut::new(0.0, 28.0, 0.0, 28.0)
61    );
62}