rotary_encoder_embedded/
standard.rs

1use embedded_hal::digital::InputPin;
2
3use crate::Direction;
4use crate::RotaryEncoder;
5
6/// StandardMode
7/// This mode is best used when polled at ~900Hz.
8#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct StandardMode {
10    /// The pin state
11    pin_state: [u8; 2],
12}
13
14// For debouncing of pins, use 0x0f (b00001111) and 0x0c (b00001100) etc.
15const PIN_MASK: u8 = 0x03;
16const PIN_EDGE: u8 = 0x02;
17
18impl<DT, CLK> RotaryEncoder<StandardMode, DT, CLK>
19where
20    DT: InputPin,
21    CLK: InputPin,
22{
23    /// Updates the `RotaryEncoder`, updating the `direction` property
24    pub fn update(&mut self) -> Direction {
25        self.mode.update(
26            self.pin_dt.is_high().unwrap_or_default(),
27            self.pin_clk.is_high().unwrap_or_default(),
28        )
29    }
30}
31
32impl StandardMode {
33    /// Initialises the StandardMode
34    pub fn new() -> Self {
35        Self {
36            pin_state: [0xFF, 2],
37        }
38    }
39
40    /// Update to determine the direction
41    pub fn update(&mut self, dt_value: bool, clk_value: bool) -> Direction {
42        self.pin_state[0] = (self.pin_state[0] << 1) | dt_value as u8;
43        self.pin_state[1] = (self.pin_state[1] << 1) | clk_value as u8;
44
45        let a = self.pin_state[0] & PIN_MASK;
46        let b = self.pin_state[1] & PIN_MASK;
47
48        let mut dir: Direction = Direction::None;
49
50        if a == PIN_EDGE && b == 0x00 {
51            dir = Direction::Anticlockwise;
52        } else if b == PIN_EDGE && a == 0x00 {
53            dir = Direction::Clockwise;
54        }
55
56        dir
57    }
58}
59
60impl<LOGIC, DT, CLK> RotaryEncoder<LOGIC, DT, CLK>
61where
62    DT: InputPin,
63    CLK: InputPin,
64{
65    /// Configure `RotaryEncoder` to use the standard API
66    pub fn into_standard_mode(self) -> RotaryEncoder<StandardMode, DT, CLK> {
67        RotaryEncoder {
68            pin_dt: self.pin_dt,
69            pin_clk: self.pin_clk,
70            mode: StandardMode::new(),
71        }
72    }
73}
74
75impl Default for StandardMode {
76    fn default() -> Self {
77        Self::new()
78    }
79}