-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathrotary_encoder.cc
70 lines (64 loc) · 1.74 KB
/
rotary_encoder.cc
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
#include "rotary_encoder.h"
#include "hardware/gpio.h"
#include "tusb.h"
#include "utils.h"
RotaryEncoder::RotaryEncoder() : RotaryEncoder(0, 0, 1) {}
RotaryEncoder::RotaryEncoder(uint8_t pin_a, uint8_t pin_b, uint8_t resolution)
: pin_a_(pin_a),
pin_b_(pin_b),
resolution_(resolution),
a_state_(false),
pulse_count_(0),
dir_(false),
is_config_(false) {
gpio_init(pin_a_);
gpio_init(pin_b_);
gpio_set_dir(pin_a_, GPIO_IN);
gpio_set_dir(pin_b_, GPIO_IN);
gpio_disable_pulls(pin_a_);
gpio_disable_pulls(pin_b_);
a_state_ = gpio_get(pin_a_);
}
void RotaryEncoder::InputTick() {
const bool a_state = gpio_get(pin_a_);
if (a_state != a_state_) {
const bool b_state = gpio_get(pin_b_);
const bool dir = a_state == b_state;
if (dir == dir_) {
if (++pulse_count_ >= resolution_) {
HandleMovement(dir);
pulse_count_ = 0;
}
} else {
dir_ = dir;
pulse_count_ = 1;
}
a_state_ = a_state;
}
}
void RotaryEncoder::SetConfigMode(bool is_config_mode) {
is_config_ = is_config_mode;
}
void RotaryEncoder::HandleMovement(bool dir) {
if (is_config_) {
if (config_modifier_ != NULL) {
if (dir) {
config_modifier_->Up();
} else {
config_modifier_->Down();
}
}
} else {
for (auto keyboard_out : *keyboard_output_) {
keyboard_out->SendConsumerKeycode(
dir ? HID_USAGE_CONSUMER_VOLUME_INCREMENT
: HID_USAGE_CONSUMER_VOLUME_DECREMENT);
}
}
}
Status RegisterEncoder(uint8_t tag, uint8_t pin_a, uint8_t pin_b,
uint8_t resolution) {
return DeviceRegistry::RegisterInputDevice(tag, [=]() {
return std::make_shared<RotaryEncoder>(pin_a, pin_b, resolution);
});
}