#include <Arduino.h>
//*************************************************************************
//Pins for rotary encoder and variables
//*************************************************************************
#define CLK_PIN 32 // ESP32 pin GPIO25 connected to the rotary encoder's CLK pin
#define DT_PIN 33 // ESP32 pin GPIO26 connected to the rotary encoder's DT pin
#define SW_PIN 34 // ESP32 pin GPIO27 connected to the rotary encoder's SW pin
#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;
//*************************************************************************
//ISR for handling button press
//*************************************************************************
void IRAM_ATTR ISR_button() {
Serial.println("Button Pressed");
}
//*************************************************************************
//ISR for handling rotary encoder
//*************************************************************************
void IRAM_ATTR ISR_encoder() {
if ((millis() - last_time) < 50) // debounce time is 50ms
return;
if (digitalRead(DT_PIN) == HIGH) {
// the encoder is rotating in counter-clockwise direction => decrease the counter
counter--;
direction = DIRECTION_CCW;
Serial.println("Counter-Clockwise");
} else {
// the encoder is rotating in clockwise direction => increase the counter
counter++;
direction = DIRECTION_CW;
Serial.println("Clockwise");
}
last_time = millis();
}
void setup() {
Serial.begin(9600);
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
pinMode(SW_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(CLK_PIN), ISR_encoder, RISING);
attachInterrupt(digitalPinToInterrupt(SW_PIN), ISR_button, FALLING);
}
void loop() {
// Main code here
}