Encoder: handle switch
parent
a9e21296c8
commit
63f57df758
|
@ -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");
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue