const int clkPin = 2; // Pin connected to CLK on the rotary encoder
const int dtPin = 3; // Pin connected to DT on the rotary encoder
const int swPin = 4; // Pin connected to SW on the rotary encoder
const int redLEDPin = 8; // Pin connected to Red LED
const int greenLEDPin = 9; // Pin connected to Green LED
int lastStateCLK;
int currentStateCLK;
int lastButtonState;
void setup() {
// Initialize LED pins as output
pinMode(redLEDPin, OUTPUT);
pinMode(greenLEDPin, OUTPUT);
// Initialize rotary encoder pins
pinMode(clkPin, INPUT);
pinMode(dtPin, INPUT);
pinMode(swPin, INPUT_PULLUP);
// Read the initial state of the CLK pin
lastStateCLK = digitalRead(clkPin);
lastButtonState = digitalRead(swPin);
// Turn off both LEDs initially
digitalWrite(redLEDPin, LOW);
digitalWrite(greenLEDPin, LOW);
}
void loop() {
// Read the current state of the CLK pin
currentStateCLK = digitalRead(clkPin);
// If the state has changed, then the encoder has been rotated
if (currentStateCLK != lastStateCLK) {
// Read the DT pin
int dtState = digitalRead(dtPin);
// Determine the direction of rotation
if (dtState != currentStateCLK) {
// Turning clockwise
digitalWrite(redLEDPin, HIGH);
digitalWrite(greenLEDPin, LOW);
} else {
// Turning counterclockwise
digitalWrite(redLEDPin, LOW);
digitalWrite(greenLEDPin, HIGH);
}
}
// Read the button state
int currentButtonState = digitalRead(swPin);
// If the button is pressed, turn off both LEDs
if (currentButtonState == LOW && lastButtonState == HIGH) {
delay(50); // Debounce delay
digitalWrite(redLEDPin, LOW);
digitalWrite(greenLEDPin, LOW);
}
// Update the last states
lastStateCLK = currentStateCLK;
lastButtonState = currentButtonState;
}