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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use crate::{Control, DebouncedInput, DebouncedInputConfig, DebouncedInputEvent, ElapsedTimer};
use core::ops::AddAssign;
use num_integer::Integer;
use num_traits::{One, Signed, Zero};
use switch_hal::InputSwitch;
pub trait EncoderConfig: DebouncedInputConfig {
type Counts: AddAssign + Integer + Signed + Copy;
const COUNTS_DIV: Self::Counts;
}
pub struct Encoder<SwitchA: InputSwitch, SwitchB: InputSwitch, Config: EncoderConfig> {
debounced_input_a: DebouncedInput<SwitchA, Config>,
debounced_input_b: DebouncedInput<SwitchB, Config>,
counts: Config::Counts,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum EncoderEvent {
NoTurn,
ClockwiseTurn,
CounterClockwiseTurn,
}
impl<SwitchA: InputSwitch, SwitchB: InputSwitch, Config: EncoderConfig>
Encoder<SwitchA, SwitchB, Config>
{
pub fn new(input_switch_a: SwitchA, input_switch_b: SwitchB) -> Self {
Encoder {
debounced_input_a: DebouncedInput::new(input_switch_a),
debounced_input_b: DebouncedInput::new(input_switch_b),
counts: Zero::zero(),
}
}
pub fn release_input_switches(self) -> (SwitchA, SwitchB) {
(
self.debounced_input_a.release_input_switch(),
self.debounced_input_b.release_input_switch(),
)
}
}
impl<SwitchA: InputSwitch, SwitchB: InputSwitch, Config: EncoderConfig> Control
for Encoder<SwitchA, SwitchB, Config>
where
SwitchA::Error: From<SwitchB::Error>,
{
type Timestamp = <Config::Timer as ElapsedTimer>::Timestamp;
type Event = EncoderEvent;
type Error = SwitchA::Error;
fn update(&mut self, now: Self::Timestamp) -> Result<Self::Event, Self::Error> {
let a_event = self.debounced_input_a.update(now.clone())?;
let b_event = self.debounced_input_b.update(now)?;
fn check_event<Counts: Signed>(
event: DebouncedInputEvent,
antogonist_state: bool,
direct: Counts,
) -> Counts {
match event {
DebouncedInputEvent::Rise if antogonist_state => -direct,
DebouncedInputEvent::Rise => direct,
DebouncedInputEvent::Fall if antogonist_state => direct,
DebouncedInputEvent::Fall => -direct,
_ => Zero::zero(),
}
}
let direct = One::one();
self.counts += check_event(a_event, self.debounced_input_b.is_high(), direct);
self.counts += check_event(b_event, self.debounced_input_a.is_high(), -direct);
let result_event = if !self.counts.is_zero() && (self.counts % Config::COUNTS_DIV).is_zero()
{
let counts = self.counts;
self.counts = Zero::zero();
match counts.is_positive() {
true => EncoderEvent::ClockwiseTurn,
false => EncoderEvent::CounterClockwiseTurn,
}
} else {
EncoderEvent::NoTurn
};
Ok(result_event)
}
}