#define ENCODER_CLK 4
#define ENCODER_DT 5
#define BTN_PIN 6
int counter = 0;
int lastClk = HIGH;
int oldBtnVal = 1; // INPUT_PULLUP idles HIGH
void checkButton() {
int btnVal = digitalRead(BTN_PIN);
if (btnVal != oldBtnVal) {
oldBtnVal = btnVal;
if (btnVal == LOW) {
Serial.println("Switch pressed");
} else {
Serial.println("Switch released");
}
delay(20);
}
}
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(BTN_PIN, INPUT_PULLUP);
}
void loop() {
checkButton();
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
counter++;
Serial.print("Rotated CW ⏩");
Serial.print("\tCounter: ");
Serial.println(counter);
}
if (newClk == LOW && dtValue == LOW) {
counter--;
Serial.print("Rotated CCW ⏪");
Serial.print("\tCounter: ");
Serial.println(counter);
}
}
}
Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1