91 lines
1.6 KiB
C++
91 lines
1.6 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
|
|
|
|
bool previousClk = false;
|
|
bool previousDt = false;
|
|
|
|
void setupEncoder() {
|
|
pinMode(CLK_PIN, INPUT);
|
|
pinMode(DT_PIN, INPUT);
|
|
pinMode(SW_PIN, INPUT_PULLUP);
|
|
|
|
// save initial state
|
|
previousClk = digitalRead(CLK_PIN);
|
|
previousDt = digitalRead(DT_PIN);
|
|
}
|
|
|
|
void handleSwitch();
|
|
|
|
void demoEncoder() {
|
|
handleSwitch();
|
|
handleEncoder();
|
|
}
|
|
|
|
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");
|
|
}
|
|
|
|
void handleEncoder() {
|
|
bool clk = digitalRead(CLK_PIN);
|
|
bool dt = digitalRead(DT_PIN);
|
|
|
|
// only handle change
|
|
if (clk == previousClk && dt == previousDt) {
|
|
return;
|
|
}
|
|
|
|
// TODO: Do we need to debounce encoder?
|
|
|
|
// clockwise pattern:
|
|
// clk: 1001 1001
|
|
// dt: 1100 1100
|
|
// counter-clockwise pattern:
|
|
// clk: 1100 1100
|
|
// dt: 1001 1001
|
|
if (clk == dt) {
|
|
if (clk == previousClk) {
|
|
Serial.println("Clockwise");
|
|
} else {
|
|
Serial.println("Counter-clockwise");
|
|
}
|
|
}
|
|
|
|
// save state
|
|
previousClk = clk;
|
|
previousDt = dt;
|
|
}
|