Encoder: Return encoder event

main
radex 2024-02-11 13:19:22 +01:00
parent 7c9323c9b8
commit efc318c99a
Signed by: radex
SSH Key Fingerprint: SHA256:hvqRXAGG1h89yqnS+cyFTLKQbzjWD4uXIqw7Y+0ws30
1 changed files with 31 additions and 15 deletions

View File

@ -14,6 +14,16 @@ When rotated clockwise, CLK changes before DT; when rotated counter-clockwise, D
#define SW_DEBOUNCE_MS 10
typedef uint8_t SwitchEvent;
#define SWITCH_NONE 0
#define SWITCH_PRESSED 1
#define SWITCH_RELEASED 2
typedef int8_t EncoderEvent;
#define ENCODER_NONE 0
#define ENCODER_CLOCKWISE 1
#define ENCODER_COUNTER_CLOCKWISE -1
bool previousClk = false;
bool previousDt = false;
@ -27,45 +37,51 @@ void setupEncoder() {
previousDt = digitalRead(DT_PIN);
}
void handleSwitch();
SwitchEvent handleSwitch();
EncoderEvent handleEncoder();
void demoEncoder() {
handleSwitch();
handleEncoder();
if (auto event = handleSwitch()) {
Serial.println(event == SWITCH_PRESSED ? "Pressed" : "Released");
}
if (auto event = handleEncoder()) {
Serial.println(event == ENCODER_CLOCKWISE ? "Clockwise" : "Counter-clockwise");
}
}
bool previousPressed = false;
unsigned long lastChangeAt = 0;
void handleSwitch() {
SwitchEvent handleSwitch() {
bool isPressed = !digitalRead(SW_PIN);
// only handle change
if (isPressed == previousPressed) {
return;
return SWITCH_NONE;
}
// debounce
unsigned long now = millis();
if (now - lastChangeAt < SW_DEBOUNCE_MS) {
return;
return SWITCH_NONE;
}
// save state
previousPressed = isPressed;
lastChangeAt = now;
// handle change
Serial.println(isPressed ? "Pressed" : "Released");
// return event
return isPressed ? SWITCH_PRESSED : SWITCH_RELEASED;
}
void handleEncoder() {
EncoderEvent handleEncoder() {
bool clk = digitalRead(CLK_PIN);
bool dt = digitalRead(DT_PIN);
// only handle change
if (clk == previousClk && dt == previousDt) {
return;
return ENCODER_NONE;
}
// TODO: Do we need to debounce encoder?
@ -76,15 +92,15 @@ void handleEncoder() {
// counter-clockwise pattern:
// clk: 1100 1100
// dt: 1001 1001
EncoderEvent event = ENCODER_NONE;
if (clk == dt) {
if (clk == previousClk) {
Serial.println("Clockwise");
} else {
Serial.println("Counter-clockwise");
}
event = clk == previousClk ? ENCODER_CLOCKWISE : ENCODER_COUNTER_CLOCKWISE;
}
// save state
previousClk = clk;
previousDt = dt;
// return event
return event;
}