#include <Arduino.h>
#include <ESP32Encoder.h>
#include <Button2.h>
/* ================== PINBELEGUNG ================== */
#define ENC_CLK 16 // Encoder A / CLK
#define ENC_DT 17 // Encoder B / DT
#define ENC_BTN 5 // Encoder Button
/* ================== OBJEKTE ================== */
ESP32Encoder encoder;
Button2 button(ENC_BTN);
/* ================== ENCODER INTERN ================== */
static int32_t lastRaw = 0;
static int32_t acc = 0;
/* ================== BUTTON INTERN ================== */
enum class BtnEvent : uint8_t {
NONE,
CLICK,
LONG
};
static volatile BtnEvent btnEvent = BtnEvent::NONE;
/* ======================================================
FERTIGE FUNKTION: Encoder
Rückgabe: -1 / 0 / +1
====================================================== */
int getEncoderStep() {
int32_t raw = encoder.getCount();
int32_t diff = raw - lastRaw;
if (diff != 0) {
lastRaw = raw;
acc += diff;
// HALF-QUAD: 2 Flanken = 1 Rastung
if (acc >= 2) {
acc -= 2;
return +1;
}
if (acc <= -2) {
acc += 2;
return -1;
}
}
return 0;
}
/* ======================================================
FERTIGE FUNKTION: Button
Rückgabe: NONE / CLICK / LONG
====================================================== */
BtnEvent getButtonEvent() {
BtnEvent ev = btnEvent;
btnEvent = BtnEvent::NONE; // Event verbrauchen
return ev;
}
/* ================== SETUP ================== */
void setup() {
Serial.begin(115200);
delay(500);
Serial.println();
Serial.println("ESP32 Encoder + Button FINAL TEST");
Serial.println("---------------------------------");
/* GPIO Pullups */
pinMode(ENC_CLK, INPUT_PULLUP);
pinMode(ENC_DT, INPUT_PULLUP);
pinMode(ENC_BTN, INPUT_PULLUP);
/* Encoder (PCNT) */
encoder.attachHalfQuad(ENC_CLK, ENC_DT);
encoder.clearCount();
/* Button Callbacks (gekapselt) */
button.setPressedHandler([](Button2&) {
btnEvent = BtnEvent::CLICK;
});
button.setLongClickHandler([](Button2&) {
btnEvent = BtnEvent::LONG;
});
Serial.println("Setup done.");
}
/* ================== LOOP ================== */
void loop() {
/* Encoder */
int step = getEncoderStep();
if (step != 0) {
Serial.print("ENC STEP = ");
Serial.println(step);
}
/* Button */
button.loop(); // MUSS zyklisch aufgerufen werden
BtnEvent ev = getButtonEvent();
if (ev == BtnEvent::CLICK) {
Serial.println("BTN: CLICK");
}
else if (ev == BtnEvent::LONG) {
Serial.println("BTN: LONG");
}
delay(5);
}