#define encCLK 7
#define encDT 8
volatile int dir;
volatile bool flag;
volatile int counter;
volatile int laststate = 1;
volatile uint64_t lastPulse;
void setup() {
Serial.begin(115200);
while (!Serial) {
delay(10);
}
pinMode(encCLK, INPUT);
pinMode(encDT, INPUT);
attachInterrupt(digitalPinToInterrupt(encCLK), encoderISR, CHANGE);
}
void encoderISR() {
uint64_t now = millis();
int state = digitalRead(encCLK);
if (state != laststate && state == LOW) {
if (now - lastPulse >= 500) {
lastPulse = now;
flag = true;
if (digitalRead(encDT) != state) {
dir = 1;
counter++;
} else {
dir = 0;
counter--;
}
}
}
laststate = state;
}
void loop() {
if (flag) {
Serial.print(dir ? "CW " : "CCW ");
Serial.println(counter);
flag = false;
}
delay(10);
}