const int btnPin = 9; // GPIO #3 - Push button on encoder
const int DT = A3; // GPIO #4 - DT on encoder (Output B)
const int CLK = A2; // GPIO #5 - CLK on encoder (Output A)
int encoderPos = 0;
int lastEncoderPos = 0;
int buttonState = HIGH;
int lastButtonState = HIGH;
unsigned long buttonPressTime = 0;
unsigned long buttonReleaseTime = 0;
unsigned long lastDebounceTime = 0;
int buttonLongPressThreshold = 1000; // 500 milliseconds for a long press
int doublePressThreshold = 500; // 300 milliseconds for a double press
void setup() {
Serial.begin(9600);
pinMode(btnPin, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
pinMode(CLK, INPUT_PULLUP);
}
void loop() {
int reading = digitalRead(btnPin);
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > 50) {
if (reading != buttonState) {
buttonState = reading;
if (buttonState == LOW) {
buttonPressTime = millis();
} else {
buttonReleaseTime = millis();
unsigned long buttonPressDuration = buttonReleaseTime - buttonPressTime;
if (buttonPressDuration < buttonLongPressThreshold) {
if (buttonPressDuration < doublePressThreshold) {
// Quick press
Serial.println("Quick push");
} else {
// Slow press
Serial.println("Slow push");
}
} else {
// Long press
Serial.println("Long push");
}
}
}
}
lastButtonState = reading;
int clkState = digitalRead(CLK);
int dtState = digitalRead(DT);
if (clkState != dtState) {
if (clkState == HIGH) {
encoderPos++;
} else {
encoderPos--;
}
if (encoderPos != lastEncoderPos) {
Serial.println(encoderPos);
lastEncoderPos = encoderPos;
}
}
delay(50); // Adjust delay as needed
}