// Rotary Encoder Inputs
#define CLK 2 // Output A
#define DT 3 // Output B
volatile int currentStateCLK;
volatile int currentStateDT;
bool lastStateCLK;
volatile int counter;
String currentDir ="";
void setup() {
// Set encoder pins as inputs
attachInterrupt(digitalPinToInterrupt(2),handler, CHANGE);
// Setup Serial Monitor
Serial.begin(9600);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
}
void loop()
{
if (currentStateCLK != lastStateCLK && currentStateCLK == 1)
{
if (digitalRead(DT) != currentStateCLK)
{
counter--;
currentDir = "CCW";
}
else
{
counter++;
currentDir = "CW";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
}
void handler(void)
{
currentStateCLK = digitalRead(CLK);
}