-
Notifications
You must be signed in to change notification settings - Fork 1
/
rotaryencoder.c
104 lines (87 loc) · 2.94 KB
/
rotaryencoder.c
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
97
98
99
100
101
102
103
#include "rotaryencoder.h"
#include <stdio.h>
#include <stdint.h>
#include "pico/stdlib.h"
//#define DEBOUNCE_EDGE 2000
//#define DEBOUNCE_REPORT 5000
#define DEBOUNCE_EDGE 100
#define DEBOUNCE_REPORT 1000
void rotary_task(rotary_encoder_t *data) {
uint32_t current_us = time_us_32();
uint8_t a = gpio_get(data->gpio_a);
uint8_t b = gpio_get(data->gpio_b);
if (data->triggered && current_us > data->wait_until) {
data->triggered = 0;
data->filtered_a = a;
}
if (a != data->last_a) {
data->triggered = 1;
data->wait_until = current_us + DEBOUNCE_EDGE;
}
// state change on filtered A
if (data->filtered_a != data->last_filtered_a) {
// only allow signal everey 5ms
if (current_us > data->wait_until_trigger) {
data->dir = 0;
if ((data->filtered_a) == b) {
//puts("R");
data->dir = 1 * data->factor;
}
else {
//puts("L");
data->dir = -1 * data->factor;
}
data->current_value += data->dir;
if (data->current_value < data->min_value) {
data->current_value = data->min_value;
}
if (data->current_value > data->max_value) {
data->current_value = data->max_value;
}
//printf("%d \r\n", data->current_value);
}
data->wait_until_trigger = current_us + DEBOUNCE_REPORT;
}
data->last_filtered_a = data->filtered_a;
data->last_a = a;
}
void rotary_task2(rotary_encoder_t *data) {
uint32_t current_us = time_us_32();
uint8_t a = gpio_get(data->gpio_a);
uint8_t b = gpio_get(data->gpio_b);
if (data->triggered && current_us > data->wait_until) {
data->triggered = 0;
data->filtered_a = a;
}
if (a != data->last_a) {
data->triggered = 1;
data->wait_until = current_us + DEBOUNCE_EDGE;
}
// state change on filtered A
if (data->filtered_a != data->last_filtered_a) {
// only allow signal everey 5ms
if (current_us > data->wait_until_trigger) {
data->dir = 0;
// only on falling edge
if ((data->filtered_a) == 0) {
if (b) {
data->dir = 1 * data->factor;
}
else {
data->dir = -1 * data->factor;
}
}
data->current_value += data->dir;
if (data->current_value < data->min_value) {
data->current_value = data->min_value;
}
if (data->current_value > data->max_value) {
data->current_value = data->max_value;
}
//printf("%d \r\n", data->current_value);
}
data->wait_until_trigger = current_us + DEBOUNCE_REPORT;
}
data->last_filtered_a = data->filtered_a;
data->last_a = a;
}