Skip to main content

continuous_blocks/
hysteresis.rs

1/// A Schmitt-trigger comparator: stays HIGH until the input drops below `low`, stays LOW
2/// until the input rises above `high` — the standard bang-bang/hysteresis-band block
3/// (block-diagram simulation tools typically offer an equivalent "Relay"/hysteresis block)
4/// used for current-mode control when there's no fixed switching frequency to modulate a duty
5/// command onto, unlike [`crate::Pid`]
6/// feeding a PWM carrier. Deliberately not a [`crate::StateSpace`]: the on/off memory is a
7/// genuine discrete latch, not a linear dynamic, the same reason [`crate::Vco`]'s wraparound
8/// is evaluated directly rather than folded into one.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub struct Hysteresis {
11    pub high: f64,
12    pub low: f64,
13}
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum HysteresisError {
17    LowExceedsHigh,
18}
19
20impl Hysteresis {
21    pub fn new(high: f64, low: f64) -> Result<Self, HysteresisError> {
22        if low > high {
23            return Err(HysteresisError::LowExceedsHigh);
24        }
25        Ok(Hysteresis { high, low })
26    }
27
28    /// Advances the latch by one step. `prev_state` is the previous step's output (`true` =
29    /// HIGH), `x` this step's input. Returns the new state.
30    pub fn step(&self, prev_state: bool, x: f64) -> bool {
31        if prev_state {
32            x >= self.low
33        } else {
34            x > self.high
35        }
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn rises_above_high_to_turn_on() {
45        let h = Hysteresis::new(1.0, -1.0).unwrap();
46        assert!(!h.step(false, 0.5));
47        assert!(h.step(false, 1.5));
48    }
49
50    #[test]
51    fn stays_on_inside_the_band() {
52        let h = Hysteresis::new(1.0, -1.0).unwrap();
53        assert!(h.step(true, 0.0));
54        assert!(h.step(true, -0.5));
55    }
56
57    #[test]
58    fn falls_below_low_to_turn_off() {
59        let h = Hysteresis::new(1.0, -1.0).unwrap();
60        assert!(!h.step(true, -1.5));
61    }
62
63    #[test]
64    fn stays_off_inside_the_band() {
65        let h = Hysteresis::new(1.0, -1.0).unwrap();
66        assert!(!h.step(false, 0.0));
67        assert!(!h.step(false, 0.9));
68    }
69
70    #[test]
71    fn boundary_values_are_inclusive_of_staying_in_the_current_state() {
72        let h = Hysteresis::new(1.0, -1.0).unwrap();
73        // exactly at low, while ON, should stay ON (>= low)
74        assert!(h.step(true, -1.0));
75        // exactly at high, while OFF, should stay OFF (> high, not >=)
76        assert!(!h.step(false, 1.0));
77    }
78
79    #[test]
80    fn low_exceeding_high_is_rejected_not_a_panic() {
81        assert_eq!(
82            Hysteresis::new(-1.0, 1.0),
83            Err(HysteresisError::LowExceedsHigh)
84        );
85    }
86}