LED running lights controlled by rotary encoder

About my hardware:

  • Arduino Uno
  • 5 orange leds (5mm) with series resistor
  • KY-040 Rotary Encoder

Here's the circuit diagram:


Application:
The leds should either turn off and on alternating from left to right or from right to left. The rotary encoder sets the direction.


Code:

int encoderPinA = 8;
int encoderPinB = 9;
int encoderPos = 0;
int encoderPinALast = LOW;
int encoderPinANow = LOW;
//Inkrementalwertgeber

int led1 = 3;
int led2 = 4;
int led3 = 5;
int led4 = 6;
int led5 = 7;
//LED Pins

int led = 3;
unsigned long previousMillis = 0;
const long interval = 500;
//LED Lauflicht

void setup() {
  pinMode (encoderPinA, INPUT_PULLUP);
  pinMode (encoderPinB, INPUT_PULLUP);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  Serial.begin (9600);
  digitalWrite(led, HIGH);
}

void loop() {
  unsigned long currentMillis = millis();
  encoderPinANow = digitalRead(encoderPinA);
  if ((encoderPinALast == HIGH) && (encoderPinANow == LOW)) {
    if ((digitalRead(encoderPinB) == HIGH)){
      encoderPos = encoderPos + 1;
      if (encoderPos >= 1) {
        encoderPos = 1;
      }
     }
    } 
    
  else {
      encoderPos = encoderPos -1;
      if (encoderPos < 0) {
        encoderPos = 0;
    }
    encoderPinALast = encoderPinANow;
  }
  

  Serial.println(encoderPos);
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    digitalWrite(led, LOW);
    if (encoderPos == 0) {
      led = led - 1;
      if (led < 3) {
        led = 7;
      }
      digitalWrite(led, HIGH);
    }

    if (encoderPos == 1) {
      led = led++;
      if (led > 8) {
        led = 3;
      }
      digitalWrite(led, HIGH);
    }
  }
}

Problem:
Nonethless what I do with the rotary encoder, the script will only perform the steps if the rotary encoder is set to left. I have no idea why I can't change the direction. Any help is appreciated.

print encoderPos when you change its value and see if it matches your expectations

you could also use this encoder library to abstract the reading of the encoder

here is an idea to work from

I also find it odd that you’re double shuffling BOTH encoderPos and the LED counter.

You can use encoderPos to count from 0 to n, then wrap around. and vice versa.

Using an array of LED pins would make the code shorter and more flexible.

Thanks for the example code.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.