#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD Display initialisieren
LiquidCrystal_I2C lcd(0x27, 16, 2);
// Rotary Encoder Pins
const int encoderPinA = 2;
const int encoderPinB = 3;
const int encoderButtonPin = 4;
// Variablen für Rotary Encoder
volatile int encoderValue = 0;
int lastEncoderValue = 0;
int countValue = 0; // Zählwert für die Anzeige
// Button State
bool buttonState = HIGH;
bool lastButtonState = HIGH;
// Button Debounce
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50; // 50 ms Entprellzeit
void setup() {
// LCD initialisieren
lcd.begin(16, 2);
lcd.backlight();
// Rotary Encoder Pins initialisieren
pinMode(encoderPinA, INPUT);
pinMode(encoderPinB, INPUT);
pinMode(encoderButtonPin, INPUT_PULLUP);
// Interrupts für den Rotary Encoder
attachInterrupt(digitalPinToInterrupt(encoderPinA), readEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), readEncoder, CHANGE);
// Anzeige initialisieren
updateDisplay();
}
void loop() {
// Encoder Wert auslesen und zählen
if (encoderValue != lastEncoderValue) {
if (encoderValue > lastEncoderValue) {
// Nach rechts gedreht
countValue++;
} else {
// Nach links gedreht
countValue--;
}
lastEncoderValue = encoderValue;
updateDisplay(); // Anzeige aktualisieren
}
// Button auslesen und Zustand anzeigen
int reading = digitalRead(encoderButtonPin);
// Entprellung für den Button
if (reading != lastButtonState) {
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
if (reading == LOW && buttonState == HIGH) {
buttonState = !buttonState; // Button-Zustand umschalten
updateDisplay(); // Anzeige aktualisieren
}
buttonState = reading;
}
lastButtonState = reading;
delay(50); // Kurze Pause für Stabilität
}
// Rotary Encoder Interrupt Routine
void readEncoder() {
static int lastMSB = LOW;
static int lastLSB = LOW;
int MSB = digitalRead(encoderPinA);
int LSB = digitalRead(encoderPinB);
// Die Drehrichtung des Encoders korrekt verarbeiten
if (MSB != lastMSB || LSB != lastLSB) {
if (MSB == LSB) {
encoderValue--; // Drehung nach links
} else {
encoderValue++; // Drehung nach rechts
}
}
lastMSB = MSB;
lastLSB = LSB;
}
// Funktion zur Aktualisierung der LCD-Anzeige
void updateDisplay() {
lcd.clear();
// Drehrichtung und Zählwert anzeigen
lcd.setCursor(0, 0);
if (encoderValue > lastEncoderValue) {
lcd.print("Right");
} else if (encoderValue < lastEncoderValue) {
lcd.print("Left ");
} else {
lcd.print("No Change");
}
lcd.setCursor(0, 1);
lcd.print("Count: ");
lcd.print(countValue);
// Button Zustand anzeigen
lcd.setCursor(12, 0);
lcd.print(buttonState ? "ON" : "OFF");
}