-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotaryEncoder.cpp
More file actions
73 lines (53 loc) · 1.53 KB
/
RotaryEncoder.cpp
File metadata and controls
73 lines (53 loc) · 1.53 KB
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
#include "RotaryEncoder.h"
//#include <arduino.h>
RotaryEncoder::RotaryEncoder(int pinClk, int pinDt, int pinSw) :
pinClk(pinClk), pinDt(pinDt), pinSw(pinSw),
lastClk(LOW), lastDt(LOW), lastSw(LOW)
{}
RotaryEncoder::Val::Val() :
value(0), valueMin(0), valueMax(100), step(1)
{}
bool RotaryEncoder::getSwitchState() const {
return lastSw == HIGH;
}
void RotaryEncoder::setup()
{
pinMode(pinClk, INPUT);
pinMode(pinDt, INPUT);
pinMode(pinSw, INPUT);
// Enable Pull-Up Resistors
digitalWrite(pinClk, HIGH);
digitalWrite(pinDt, HIGH);
digitalWrite(pinSw, HIGH);
}
// Returns whether value has changed
bool RotaryEncoder::update()
{
bool valueChanged = false;
// Always read switch
lastSw = digitalRead(pinSw);
// Sample data when clock changes
int clk = digitalRead(pinClk);
if(clk == lastClk)
return false;
lastClk = clk;
int dt = digitalRead(pinDt);
if(dt == lastDt)
return false;
lastDt = dt;
// Only pay attention to Clk Low-High transition
if(clk != HIGH)
return false;
// Process switch
Val& val = (lastSw == STATE_VAL1) ? value1 : value2;
if(dt == HIGH)
val.value += val.step;
else
val.value -= val.step;
val.value = constrain(val.value, val.valueMin, val.valueMax);
/*Serial.print("Value ");
Serial.print((lastSw==STATE_VAL1) ? "1 (brightness)" : "2 (sensitivity)");
Serial.print(" changed to: ");
Serial.println(val.value);*/
return true;
}