#include <Arduino.h>
// Define the pins for the rotary encoder
const int CLK_PIN = 2; // Connect CLK to D2
const int DT_PIN = 3; // Connect DT to D3
// Variables to keep track of the encoder state
int lastStateCLK = LOW;
int counter = 0;
void setup() {
// Initialize the pins as inputs
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
// Enable internal pull-up resistors
digitalWrite(CLK_PIN, HIGH);
digitalWrite(DT_PIN, HIGH);
// Start the serial communication
Serial.begin(9600);
}
void loop() {
// Read the current state of the CLK pin
int currentStateCLK = digitalRead(CLK_PIN);
// Check for a change in the CLK pin
if (currentStateCLK != lastStateCLK) {
// If the DT pin is different from the CLK pin, it's a clockwise rotation
if (digitalRead(DT_PIN) != currentStateCLK) {
counter++;
} else {
// It's a counterclockwise rotation
counter--;
}
// Print the current counter value
Serial.println("Counter: " + String(counter));
}
// Update the last state of the CLK pin
lastStateCLK = currentStateCLK;
}