-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathencoder.cpp
More file actions
96 lines (74 loc) · 2.38 KB
/
encoder.cpp
File metadata and controls
96 lines (74 loc) · 2.38 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Rotary Encoder
// Implements interface functions
#include "encoder.h"
Encoder::~Encoder() {
};
Encoder::Encoder(int clkPin, int dtPin, int swPin) {
this->clk_pin = clkPin;
this->dt_pin = dtPin;
this->sw_pin = swPin;
};
int Encoder::initRotaryEncoder() {
pinMode(this->clk_pin, INPUT);
pinMode(this->dt_pin, INPUT);
pinMode(this->sw_pin, INPUT);
encoderPreviousCLK = digitalRead(this->clk_pin); // Initial CLK state
encoderPreviousSW = digitalRead(this->sw_pin); // Initial SW state
return 0;
}
// Getters & Setters
bool Encoder::toggled() {
return currentlyToggled;
}
bool Encoder::momentaryOn() {
return currentlyMomentaryOn;
}
// Public Methods
void Encoder::readEncoderSwitch(void (*encoderSwitchMomentaryHandler)()) {
encoderCurrentSW = digitalRead(this->sw_pin);
// If the SW didn't change, then the encoder wasn't pressed or released. Do nothing.
if (encoderCurrentSW == encoderPreviousSW) {
return;
}
if (encoderCurrentSW == LOW) {
Serial.println("Encoder Pressed");
currentlyToggled = !currentlyToggled;
// Trigger a momentary handler if one is supplied
encoderSwitchMomentaryHandler();
}
if (encoderCurrentSW == HIGH) {
Serial.println("Encoder Released");
}
encoderPreviousSW = encoderCurrentSW;
}
// TODO: Make function argument optional
void Encoder::readEncoderSwitchMomentary(void (*encoderSwitchMomentaryHandler)()) {
// If the SW didn't change, then the encoder wasn't pressed or released. Do nothing.
if (encoderCurrentSW == encoderPreviousSW) {
return;
}
if (encoderCurrentSW == LOW) {
Serial.println("Encoder Pressed");
encoderSwitchMomentaryHandler();
}
}
void Encoder::readEncoderRotation(void (*clockwiseHandler)(), void (*counterclockwiseHandler)()) {
encoderCurrentCLK = digitalRead(this->clk_pin);
// If the CLK didn't change, then the encoder didn't move. Do nothing.
if (encoderCurrentCLK == encoderPreviousCLK) {
return;
}
encoderPreviousCLK = encoderCurrentCLK;
// Extremely basic debounce.
// Current encoder only latches on 1 and reads 0 when not latched.
// Only compute rotation when the encoder latches.
if (encoderCurrentCLK == 0) {
return;
}
// Both CLK and DT are HIGH when rotating counterclockwise
if (encoderCurrentCLK == digitalRead(this->dt_pin)) { // Counterclockwise
counterclockwiseHandler();
} else { // Clockwise
clockwiseHandler();
}
}