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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#![doc(html_root_url = "https://docs.rs/rotary-encoder-hal/0.2.1")]
#![deny(missing_docs)]
#![deny(warnings)]
#![no_std]
use either::Either;
use embedded_hal as hal;
use hal::digital::v2::InputPin;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Rotary<A, B> {
pin_a: A,
pin_b: B,
state: u8,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Direction {
Clockwise,
CounterClockwise,
None,
}
impl From<u8> for Direction {
fn from(s: u8) -> Self {
match s {
0b0001 | 0b0111 | 0b1000 | 0b1110 => Direction::Clockwise,
0b0010 | 0b0100 | 0b1011 | 0b1101 => Direction::CounterClockwise,
_ => Direction::None,
}
}
}
impl<A, B> Rotary<A, B>
where
A: InputPin,
B: InputPin,
{
pub fn new(pin_a: A, pin_b: B) -> Self {
Self {
pin_a,
pin_b,
state: 0u8,
}
}
pub fn update(&mut self) -> Result<Direction, Either<A::Error, B::Error>> {
let mut s = self.state & 0b11;
if self.pin_a.is_low().map_err(Either::Left)? {
s |= 0b100;
}
if self.pin_b.is_low().map_err(Either::Right)? {
s |= 0b1000;
}
self.state = s >> 2;
Ok(s.into())
}
}