// Rotary Encoder Inputs
#define CLK 31
#define DT 33
#define encoderBtn 35
int counter = 0;
bool cwMove = false; // flag to check if encoder is moved in cw direction
bool ccwMove = false; // flag to check if encoder is moved in ccw direciton
int currentStateCLK;
int lastStateCLK;
void setup() {
Serial.begin(9600);
pinMode(encoderBtn, INPUT_PULLUP);
// Set encoder pins as inputs
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
// Read the initial state of CLK
lastStateCLK = digitalRead(CLK);
// // Call updateEncoder() when any high/low changed seen
// // on interrupt 0 (pin 2), or interrupt 1 (pin 3)
// attachInterrupt(0, updateEncoder, CHANGE);
// attachInterrupt(1, updateEncoder, CHANGE);
}
void loop() {
updateEncoder();
if (cwMove) { // Check if encoder is moved in cw direciton
cwMove = false; // reset flag
counter += 1;
Serial.print("Counter:");
Serial.println(counter);
} else if (ccwMove) { // Check if encoder is moved in ccw direciton
ccwMove = false; // reset flag
counter -= 1;
Serial.print("Counter:");
Serial.println(counter);
}
}
void updateEncoder() {
// 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 the DT state is different than the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(DT) != currentStateCLK) {
ccwMove = true; // set ccw movement as true
} else {
// Encoder is rotating CW so increment
cwMove = true; // set cw movement as true
}
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}