// Define pins for the rotary encoder
const int encoderPinA = 2; // CLK pin
const int encoderPinB = 3; // DT pin
// Variable to store the counter value
volatile int counter = 0;
// Variable to store the last state of CLK pin
volatile int lastStateCLK = LOW;
void setup() {
// Initialize Serial communication
Serial.begin(9600);
// Set encoder pins as inputs
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
// Enable internal pullup resistors
digitalWrite(encoderPinA, HIGH);
digitalWrite(encoderPinB, HIGH);
// Attach interrupt to CLK pin (pin 2)
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
// Read the initial state of CLK
lastStateCLK = digitalRead(encoderPinA);
// Print the initial counter value
Serial.print("Initial counter value: ");
Serial.println(counter);
}
void loop() {
// The main loop can be empty as we're using interrupts
// You can add other code here if needed
}
void updateEncoder() {
// Read the current state of CLK
int currentStateCLK = digitalRead(encoderPinA);
// 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 the same as the CLK state then
// the encoder is rotating CCW so decrement
if (digitalRead(encoderPinB) == currentStateCLK) {
counter --;
} else {
// Encoder is rotating CW so increment
counter ++;
}
Serial.print("Counter: ");
Serial.println(counter);
}
// Remember last CLK state
lastStateCLK = currentStateCLK;
}