// === PIN DEFINITIONS ===
int CLK = 4; // Clock pin of rotary encoder
int DT = 5; // Data pin of rotary encoder
int SW = 6; // Pushbutton (optional)
int LED_PIN = 13; // Built-in LED for feedback
// === STATE VARIABLES ===
int lastCLK = HIGH; // Previous state of CLK
int currentCLK;
int currentDT;
unsigned long lastDebounceTime = 0;
const int debounceDelay = 10; // milliseconds
void setup() {
// Initialize pins
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
pinMode(SW, INPUT_PULLUP);
pinMode(LED_PIN, OUTPUT);
// Start serial communication
Serial.begin(9600);
while (!Serial); // Wait for serial monitor (useful for Nano with CH340)
// Initial read
lastCLK = digitalRead(CLK);
// Let user know we started
Serial.println("🟢 Rotary Encoder Debug Mode");
Serial.println("Rotate the knob and watch for output...");
Serial.println("Format: [CLK | DT] → Direction");
}
void loop() {
unsigned long currentTime = millis();
// Debounce delay - poll every 10ms
if (currentTime - lastDebounceTime < debounceDelay) {
return;
}
lastDebounceTime = currentTime;
// Read both pins
currentCLK = digitalRead(CLK);
currentDT = digitalRead(DT);
// Detect rising or falling edge on CLK
if (currentCLK != lastCLK) {
// Small extra delay for stability (simulate hysteresis)
delayMicroseconds(500); // Half a millisecond stabilizes contact
int stableCLK = digitalRead(CLK);
int stableDT = digitalRead(DT);
// Re-check after stabilization
if (stableCLK == currentCLK) { // Confirmed change
if (stableCLK != lastCLK) {
// Determine direction based on DT relative to CLK
if (stableDT != stableCLK) {
Serial.println("[↗️ CW] Clockwise Rotation Detected!");
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED
} else {
Serial.println("[↙️ CCW] Counterclockwise Rotation Detected!");
digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED
}
// Optional: show raw values
Serial.print(" CLK=");
Serial.print(stableCLK);
Serial.print(" DT=");
Serial.println(stableDT);
}
}
// Update last state
lastCLK = stableCLK;
}
// Optionally check switch press
if (digitalRead(SW) == LOW) {
Serial.println("🔘 PUSH BUTTON PRESSED!");
delay(300); // Simple debounce
}
}