// Rotary Encoder Inputs
#define CLK 2 // Output A
#define DT 3 // Output B
int counter = 0;
int currentStateCLK;
int lastStateCLK;
String currentDir ="";
unsigned long lastButtonPress = 0;
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);
// Adding interrupt on a CHANGE event
// This is because our original code only cares when the state of CLK changes
attachInterrupt(digitalPinToInterrupt(CLK), CalcDirection, CHANGE);
}
void loop()
{}
void CalcDirection() {
// Read the current state of CLK
currentStateCLK = digitalRead(CLK);
// If last and current state of CLK are different, then pulse occurred
// React to only 1 state change to avoid double count
if (currentStateCLK != lastStateCLK && currentStateCLK == 1){
//if ((lastStateCLK == LOW) && (currentStateCLK == HIGH)){
// If the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
//if (digitalRead(DT) == HIGH){
counter ++;
currentDir ="CW";
} else {
// Encoder is rotating CCW so decrement
counter --;
currentDir ="CCW";
}
Serial.print("Direction: ");
Serial.print(currentDir);
Serial.print(" | Counter: ");
Serial.println(counter);
}
//}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}