// Rotary Encoder Inputs
#define CLK 2 // Output A
#define DT 3 // Output B
volatile int counter = 0;
int lastStateCLK;
String currentDir = "";
void setup()
{
// Set encoder pins as inputs
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// Attach interrupts to the CLK and DT pins
attachInterrupt(digitalPinToInterrupt(CLK), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(DT), updateEncoder, CHANGE);
}
void loop()
{
// Display the counter and direction
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
delay(100); // Small delay to avoid overwhelming the serial output
}
void updateEncoder()
{
// Read the current state of CLK
int currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
if (currentStateCLK != lastStateCLK)
{
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
counter--;
currentDir = "CCW";
} else {
// Encoder is rotating CW so increment
counter++;
currentDir = "CW";
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}
}