summaryrefslogtreecommitdiffstats
path: root/firmware/src/pi.rs
blob: b9c41e8ed2796f2a9f2b2384e9d2837d705c9d66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
use crate::{
    fixpt::Fixpt,
    mutex::{MainCtx, MutexCell},
};

#[derive(Clone)]
pub struct PiParams {
    pub kp: Fixpt,
    pub ki: Fixpt,
    pub ilim: Fixpt,
}

pub struct Pi {
    i: MutexCell<Fixpt>,
}

impl Pi {
    pub const fn new() -> Self {
        Self {
            i: MutexCell::new(Fixpt::from_int(0)),
        }
    }

    pub fn run(&self, m: &MainCtx<'_>, params: &PiParams, sp: Fixpt, r: Fixpt) -> Fixpt {
        // deviation
        let e = sp - r;

        // P term
        let p = params.kp * e;

        // I term
        let i = self.i.get(m) + (params.ki * e);
        let i = i.min(params.ilim);
        let i = i.max(-params.ilim);
        self.i.set(m, i);

        p + i
    }
}

// vim: ts=4 sw=4 expandtab
bues.ch cgit interface