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.