-
Notifications
You must be signed in to change notification settings - Fork 0
/
CoreEncoder.cpp
83 lines (81 loc) · 2.63 KB
/
CoreEncoder.cpp
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
#include "CoreEncoder.h"
//--------------------------------------------------------------------------------------------------------------------------------------
Encoder::Encoder(byte p0, byte p1, byte pulsesPerClick, bool _pullup)
{
pin0 = p0;
pin1 = p1;
ppc = pulsesPerClick;
change = 0;
state = 0;
pullup = _pullup;
}
//--------------------------------------------------------------------------------------------------------------------------------------
void Encoder::begin()
{
pinMode(pin0, INPUT);
pinMode(pin1, INPUT);
if(pullup)
{
digitalWrite(pin0, HIGH); // включаем подтягивающие резисторы
digitalWrite(pin1, HIGH);
}
change = 0;
delay(10); // читаем состояние после небольшого ожидания
state = readState();
}
//--------------------------------------------------------------------------------------------------------------------------------------
void Encoder::update()
{
// State transition table. Each entry has the following meaning:
// 0 - the encoder hasn't moved
// 1 - the encoder has moved 1 unit clockwise
// -1 = the encoder has moved 1 unit anticlockwise
// 2 = illegal transition, we must have missed a state
static int tbl[16] =
{ 0, +1, -1, 0, // position 3 = 00 to 11, can't really do anything, so 0
-1, 0, -2, +1, // position 2 = 01 to 10, assume it was a bounce and should be 01 -> 00 -> 10
+1, +2, 0, -1, // position 1 = 10 to 01, assume it was a bounce and should be 10 -> 00 -> 01
0, -1, +1, 0 // position 0 = 11 to 10, can't really do anything
};
unsigned int t = readState();
int movement = tbl[(state << 2) | t];
if (movement != 0)
{
change += movement;
state = t;
}
}
//--------------------------------------------------------------------------------------------------------------------------------------
unsigned int Encoder::readState()
{
if(pullup)
{
return (digitalRead(pin0) ? 1u : 0u) | (digitalRead(pin1) ? 2u : 0u);
}
else
{
return (!digitalRead(pin0) ? 1u : 0u) | (!digitalRead(pin1) ? 2u : 0u);
}
}
//--------------------------------------------------------------------------------------------------------------------------------------
int Encoder::getChange()
{
int r;
noInterrupts();
if (change >= ppc - 1)
{
r = (change + 1)/ppc;
}
else if (change <= 1 - ppc)
{
r = -((1 - change)/ppc);
}
else
{
r = 0;
}
change -= (r * ppc);
interrupts();
return r;
}
//--------------------------------------------------------------------------------------------------------------------------------------