-
Notifications
You must be signed in to change notification settings - Fork 0
/
RotaryEncoder.hpp
58 lines (41 loc) · 1.16 KB
/
RotaryEncoder.hpp
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
#ifndef ROTARY_ENCODER_HPP
#define ROTARY_ENCODER_HPP
class RotaryEncoder{
private:
inline static const uint8_t s_FINALSTATE_CW = 6;
inline static const uint8_t s_FINALSTATE_CCW = 7;
inline static const int8_t s_transition_table[] = {
0, 0, 0, 1,
-1, 1, 2, 0,
2, 0, -2, -2,
2, -3, 0, -3,
0, -4, 2, -4,
0, 2, -5, -5,
-6, -6, -6, -6,
-7, -7, -7, -7
};
public:
RotaryEncoder(){};
RotaryEncoder(int32_t pos){
m_pos = pos;
}
void update(bool state_a, bool state_b){
uint8_t input = state_a | (state_b << 1);
m_state += s_transition_table[(input | (m_state << 2))];
if((m_state & (1 << 2)) && (m_state & (1 << 1))){
if(m_state == s_FINALSTATE_CW){
m_pos++;
}else if(m_state == s_FINALSTATE_CCW){
m_pos--;
}
m_new_pos = true;
}
}
bool new_pos(){ return m_new_pos; };
int32_t pos(bool consume = false){ if(consume) m_new_pos = false; return m_pos; }
uint8_t m_state{ 0 };
private:
int32_t m_pos{ 0 };
bool m_new_pos{ false };
};
#endif