// Define pins for the encoder and switch #define CLK_PIN A2 #define DT_PIN A1 #define SW_PIN D9 // Variables to store encoder state volatile int encoderPos = 0; volatile int lastCLKState = LOW; volatile bool lastSWState = HIGH; // Initialize switch state to HIGH (not pressed) void setup() { Serial.begin(9600); // Start serial communication pinMode(CLK_PIN, INPUT_PULLUP); // Set encoder pins as inputs with pull-up resistors pinMode(DT_PIN, INPUT_PULLUP); pinMode(SW_PIN, INPUT_PULLUP); } void loop() { // Read the state of the CLK pin int CLKState = digitalRead(CLK_PIN); // Detect rising edge of CLK if (CLKState != lastCLKState && CLKState == HIGH) { // If the DT pin is high, the encoder is rotating clockwise if (digitalRead(DT_PIN) == HIGH) { encoderPos++; } else { // Otherwise, the encoder is rotating counterclockwise encoderPos--; } } // Read the state of the switch bool SWState = digitalRead(SW_PIN); // Detect falling edge of the switch (button press) if (SWState != lastSWState && SWState == LOW) { // Print encoder position when the switch is pressed Serial.println("Switch pressed. Encoder position: " + String(encoderPos)); } lastCLKState = CLKState; lastSWState = SWState; }