#define ENCODER_CLK 10
#define ENCODER_DT 11
#define ENCODER_BTN 23
int counter = 0;
volatile int state = 0;
// void IRAM_ATTR readEncoder() {
// int dtValue = digitalRead(ENCODER_DT);
// if (dtValue == HIGH) {
// Serial.println("Rotated clockwise");
// }
// if (dtValue == LOW) {
// Serial.println("Rotated counterclockwise ⏪");
// }
// }
void IRAM_ATTR readEncoder() {
int dtValue = digitalRead(ENCODER_DT);
if (dtValue == HIGH) {
counter++; // Clockwise
state = 1;
}
if (dtValue == LOW) {
counter--; // Counterclockwise
state = 1;
}
}
// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_BTN, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}
//int lastClk = HIGH;
void loop() {
// 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) {
// Serial.println("Rotated clockwise ⏩");
// }
// if (newClk == LOW && dtValue == LOW) {
// Serial.println("Rotated counterclockwise ⏪");
// }
// }
if (state == 1){
state = 0;
Serial.println(getCounter());
}
if (digitalRead(ENCODER_BTN) == LOW) {
digitalWrite(LED_BUILTIN, HIGH);
} else {
digitalWrite(LED_BUILTIN, LOW);
}
}