64 lines
1.1 KiB
C++
64 lines
1.1 KiB
C++
#include <Arduino.h>
|
|
|
|
#include "constants.h"
|
|
|
|
/*
|
|
|
|
SW - Switch, goes low when pressed
|
|
|
|
CLK and DT from high to low, and so on when rotated
|
|
|
|
When rotated clockwise, CLK changes before DT; when rotated counter-clockwise, DT changes before CLK
|
|
|
|
*/
|
|
|
|
#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);
|
|
bool sw = digitalRead(SW_PIN);
|
|
|
|
Serial.print("CLK: ");
|
|
Serial.print(clk);
|
|
Serial.print(" DT: ");
|
|
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");
|
|
}
|