// Pin assignments
const int encoderPinA = 2; // Interrupt pin for Encoder A
const int encoderPinB = 3; // Interrupt pin for Encoder B
const int ledCW = 9; // LED for clockwise direction
const int ledCCW = 10; // LED for counterclockwise direction
const int ledIdle = 11; // LED for idle state
// Variables
volatile long lastEncoderChange = 0; // Last time the encoder moved
const long idleTimeout = 1000; // 2 seconds in milliseconds
void setup() {
// Set the pin modes
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pinMode(ledCW, OUTPUT);
pinMode(ledCCW, OUTPUT);
pinMode(ledIdle, OUTPUT);
digitalWrite(ledIdle, HIGH);
// Attach interrupts for the rotary encoder
attachInterrupt(digitalPinToInterrupt(encoderPinA), encoderMoved, CHANGE);
}
void loop() {
long currentTime = millis();
// If there's no movement for more than 2 seconds, turn on the idle LED
if (currentTime - lastEncoderChange > idleTimeout) {
digitalWrite(ledCW, LOW);
digitalWrite(ledCCW, LOW);
digitalWrite(ledIdle, HIGH);
}
}
// ISR for encoder movement
void encoderMoved() {
lastEncoderChange = millis(); // Update the last movement time
bool a = digitalRead(encoderPinA);
bool b = digitalRead(encoderPinB);
// Determine the direction based on quadrature signals
if (a == b) {
// Clockwise
digitalWrite(ledCW, HIGH);
digitalWrite(ledCCW, LOW);
digitalWrite(ledIdle, LOW); // Turn off the idle LED
} else {
// Counterclockwise
digitalWrite(ledCW, LOW);
digitalWrite(ledCCW, HIGH);
digitalWrite(ledIdle, LOW); // Turn off the idle LED
}
}