/*
Forum: https://forum.arduino.cc/t/using-rotary-pot-without-software/1368008/10
Wokwi: https://wokwi.com/projects/426596353318405121
Modified from
// KY-040 Rotary Encoder Example
// Taken from: https://docs.wokwi.com/parts/wokwi-ky-040
// Copyright (C) 2021, Uri Shaked
to control a number of leds by rotary encoder
by ec2021
2025/03/27
*/
constexpr byte ENCODER_CLK {2};
constexpr byte ENCODER_DT {3};
int lastClk = HIGH;
const byte leds[] = {13, 12, 11, 10};
const int noOfLeds = sizeof(leds) / sizeof(leds[0]);
int actLed = 0;
int lastLed = 0;
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
for (int i = 0; i < noOfLeds; i++) {
pinMode(leds[i], OUTPUT);
}
digitalWrite(leds[0], HIGH);
}
void handleEncoder() {
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
int dtValue = digitalRead(ENCODER_DT);
if (newClk == LOW && dtValue == HIGH) {
Serial.println("Rotated clockwise ⏩");
actLed++;
if (actLed >= noOfLeds) {
actLed = 0; // This starts again with the first led in the array
// actLed = noOfLeds-1; // This would stop at the last led in the array
}
}
if (newClk == LOW && dtValue == LOW) {
Serial.println("Rotated counterclockwise ⏪");
actLed--;
if (actLed < 0) {
actLed = noOfLeds - 1; // This jumps to the last led in the array
// actLed = 0; // This would stop at the first led in the array
}
}
if (lastLed != actLed) {
digitalWrite(leds[lastLed], LOW);
digitalWrite(leds[actLed], HIGH);
lastLed = actLed;
}
}
}
void loop() {
handleEncoder();
}