#define CLK 26
#define DT 14
#define SEL 27
int a;
int b;
int count;
int lastastate;
int currentastate;
#define DIRECTION_CW 0 // clockwise direction
#define DIRECTION_CCW 1 // counter-clockwise direction
// volatile int counter = 0;
volatile int direction = DIRECTION_CW;
// volatile unsigned long last_time; // for debouncing
// int prev_counter;
//ezButton button(SW_PIN); // create ezButton object that attach to pin 7;
void IRAM_ATTR ISR_encoder() {
if ((millis() - lastastate) < 50) // debounce time is 50ms
return;
if (digitalRead(DT) == HIGH) {
// the encoder is rotating in counter-clockwise direction => decrease the counter
count--;
direction = DIRECTION_CCW;
} else {
// the encoder is rotating in clockwise direction => increase the counter
count++;
direction = DIRECTION_CW;
}
lastastate = millis();
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
lastastate = millis();
b = digitalRead(DT);
count = 0;
attachInterrupt(digitalPinToInterrupt(CLK), ISR_encoder, RISING);
}
void loop() {
// digitalWrite(CLOCK, LOW);
// Serial.println("First encoder");
// Serial.print(a);
// Serial.print(b);
// Serial.println();
// delay(10); // this speeds up the simulation
// digitalWrite(CLOCK, HIGH);
currentastate = digitalRead(CLK);
if(lastastate != currentastate)
{
if(direction == DIRECTION_CW)
{
Serial.println("turned once cw");
Serial.print("Count: ");
Serial.println(count);
}
else
{
Serial.println("turned once ccw");
Serial.print("Count: ");
Serial.println(count);
}
}
lastastate = currentastate;
delay(10);
}