Encoder: handle switch

main
radex 2024-02-11 12:32:50 +01:00
parent a9e21296c8
commit 63f57df758
Signed by: radex
SSH Key Fingerprint: SHA256:hvqRXAGG1h89yqnS+cyFTLKQbzjWD4uXIqw7Y+0ws30
1 changed files with 31 additions and 0 deletions

View File

@ -12,12 +12,16 @@ When rotated clockwise, CLK changes before DT; when rotated counter-clockwise, D
*/
#define SW_DEBOUNCE_MS 10
void setupEncoder() {
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
pinMode(SW_PIN, INPUT_PULLUP);
}
void handleSwitch();
void demoEncoder() {
bool clk = digitalRead(CLK_PIN);
bool dt = digitalRead(DT_PIN);
@ -29,4 +33,31 @@ void demoEncoder() {
Serial.print(dt);
Serial.print(" SW: ");
Serial.println(sw);
handleSwitch();
}
bool previousPressed = false;
unsigned long lastChangeAt = 0;
void handleSwitch() {
bool isPressed = !digitalRead(SW_PIN);
// only handle change
if (isPressed == previousPressed) {
return;
}
// debounce
unsigned long now = millis();
if (now - lastChangeAt < SW_DEBOUNCE_MS) {
return;
}
// save state
previousPressed = isPressed;
lastChangeAt = now;
// handle change
Serial.println(isPressed ? "Pressed" : "Released");
}