forked from ardyesp/DLO-138
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoder.ino
97 lines (71 loc) · 1.75 KB
/
encoder.ino
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
/* Rotary encoder methods
CW CCW
01 00
11 10
10 11
00 01
*/
int encoderVal = 0;
// ------------------------
// called by ISR
int getEncoderSteps() {
// ------------------------
static int encoderPrevVal = 0;
int newCount = encoderVal - encoderPrevVal;
// 4 ticks make one step in rotary encoder
int numSteps = newCount / 4;
int remainder = newCount % 4;
encoderPrevVal = encoderVal - remainder;
return numSteps;
}
// ------------------------
// ISR
void readEncoderISR() {
// ------------------------
static byte lastPos = 0b00;
byte aNow = digitalRead(ENCODER_A);
byte bNow = digitalRead(ENCODER_B);
byte posNow = aNow << 1 | bNow;
if((lastPos == 0b01) && (posNow == 0b11))
encoderVal++;
else if((lastPos == 0b11) && (posNow == 0b10))
encoderVal++;
else if((lastPos == 0b10) && (posNow == 0b00))
encoderVal++;
else if((lastPos == 0b00) && (posNow == 0b01))
encoderVal++;
else if((lastPos == 0b00) && (posNow == 0b10))
encoderVal--;
else if((lastPos == 0b10) && (posNow == 0b11))
encoderVal--;
else if((lastPos == 0b11) && (posNow == 0b01))
encoderVal--;
else if((lastPos == 0b01) && (posNow == 0b00))
encoderVal--;
lastPos = posNow;
// convert the encoder reading into rounded steps
int steps = getEncoderSteps();
if(steps != 0) {
// take action
encoderChanged(steps);
}
}
long lastABPress = 0;
// ------------------------
// ISR
void readASwitchISR() {
// ------------------------
if(millis() - lastABPress < BTN_DEBOUNCE_TIME)
return;
lastABPress = millis();
encoderChanged(-1);
}
// ------------------------
// ISR
void readBSwitchISR() {
// ------------------------
if(millis() - lastABPress < BTN_DEBOUNCE_TIME)
return;
lastABPress = millis();
encoderChanged(1);
}