forked from dawsonjon/PicoRX
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbutton_encoder.cpp
More file actions
80 lines (69 loc) · 1.84 KB
/
button_encoder.cpp
File metadata and controls
80 lines (69 loc) · 1.84 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
#include "button_encoder.h"
#include <algorithm>
//#include "ui.h"
#include "pins.h"
static const uint32_t LEVELS = 6;
static const uint32_t TRESHOLD_US = 1000000;
static const uint32_t rates[LEVELS] = {200000, 100000, 50000,
20000, 20000, 20000};
static const uint8_t increments[LEVELS] = {1, 1, 1, 1, 2, 4};
button_encoder::button_encoder(s_global_settings &settings)
: encoder(settings) {
gpio_init(PIN_AB);
gpio_set_dir(PIN_AB, GPIO_IN);
gpio_pull_up(PIN_AB);
gpio_init(PIN_B);
gpio_set_dir(PIN_B, GPIO_IN);
gpio_pull_up(PIN_B);
}
int32_t button_encoder::get_change(void) {
int32_t delta = new_position - old_position;
old_position = new_position;
if (settings.reverse_encoder) {
return -delta;
} else {
return delta;
}
}
void button_encoder::update(void) {
const uint32_t now = time_us_32();
switch (state) {
case idle:
if (!gpio_get(PIN_AB)) {
start_time = now;
update_time = now;
state = right;
new_position++;
} else if (!gpio_get(PIN_B)) {
start_time = now;
update_time = now;
state = left;
new_position--;
}
break;
case right:
if (gpio_get(PIN_AB)) {
state = idle;
} else {
const uint32_t level =
std::min((now - start_time) / TRESHOLD_US, LEVELS - 1);
if ((now - update_time) > rates[level]) {
new_position += increments[level];
update_time = now;
}
}
break;
case left:
if (gpio_get(PIN_B)) {
state = idle;
} else {
const uint32_t level =
std::min((now - start_time) / TRESHOLD_US, LEVELS - 1);
if ((now - update_time) > rates[level]) {
new_position -= increments[level];
update_time = now;
}
}
break;
}
}