-
Notifications
You must be signed in to change notification settings - Fork 0
/
Rotary_KY040_final.ino
94 lines (62 loc) · 1.31 KB
/
Rotary_KY040_final.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
int DATApin = 6;
int CLOCKpin = 7;
int dataValue = -1;
int clockValue = -1;
int dataPrev = -1;
int clockPrev = -1;
int bufferLevel = 5;
int resultValue = 0;
boolean turnDetected = false;
void setup() {
pinMode(DATApin, INPUT);
pinMode(CLOCKpin, INPUT);
Serial.begin(19200);
while (! Serial);
Serial.println("System initiated...\n");
}
void loop() {
sample();
if (turnDetected) determineDirection();
}
void sample() {
dataPrev = dataValue;
clockPrev = clockValue;
dataValue = digitalRead(DATApin);
clockValue = digitalRead(CLOCKpin);
if ((dataValue != dataPrev) || (clockValue != clockPrev)) turnDetected = true;
}
void determineDirection() {
turnDetected = false;
boolean isCW;
if (dataValue == clockValue) {
isCW = (dataValue == dataPrev);
} else {
isCW = (clockValue == clockPrev);
}
if (isCW) {
bufferLevel++;
} else {
bufferLevel--;
}
interpretBuffer();
}
void interpretBuffer() {
if (bufferLevel == 0) { // full complement of CCW
bufferLevel = 5;
decrease();
return;
}
if (bufferLevel == 10) { // full complement of CW
bufferLevel = 5;
increase();
return;
}
}
void increase() {
resultValue++;
Serial.println(resultValue);
}
void decrease() {
resultValue--;
Serial.println(resultValue);
}