// Sketch: Testprogramm_Rotary-Encoder_0-19_LCD.ino
// Version 1.0 'funktioniert'
// Funktion: zählt vor und zurück von 0 bis 19, Positionszähler mit Encoder-Taster auf 0 rücksetzbar
// Breadboard: Arduino Nano
// 24.02.2024
// Copyright: Rolf Kaden
#include <Arduino.h> // Arduino Biblithek hochladen
#include <Wire.h> // Wire Bibliothek hochladen
#include <LiquidCrystal_I2C.h> // LiquidCrystal_I2C Bibliothek hochladen, Version 1.1.2
LiquidCrystal_I2C lcd(0x27, 20, 2); // Hier wird das Display benannt (Adresse/Zeichen pro Zeile/Anzahl Zeilen).
const int pinA = 2; // Pin-Definitionen
const int pinB = 3; // " "
const int encoderButtonPin = 5; // " "
volatile byte encoderPos = 0; // Variablen für den Encoder
volatile byte oldEncPos = 0; // " " " "
volatile bool aFlag = false; // " " " "
volatile bool bFlag = false; // " " " "
unsigned long lastButtonPress = 0; // Zeitstempel für den Encoder-Taster
void setup() {
pinMode(pinA, INPUT);
pinMode(pinB, INPUT);
pinMode(encoderButtonPin, INPUT);
lcd.init(); // LCD-Display starten
lcd.backlight(); // Hintergrundbeleuchtung einschalten (0 schaltet die Beleuchtung aus).
lcd.print(encoderPos); // Wert von encoderPos ausgeben (hier die 0)
lcd.setCursor(0,1); //
lcd.print("Startposition"); //
attachInterrupt(digitalPinToInterrupt(pinA), PinA, RISING); // Interrupt konfigurieren
attachInterrupt(digitalPinToInterrupt(pinB), PinB, RISING); // Interrupt konfigurieren
}
// ------------------------------------------------------------------------------------------------------------------------------------
void loop() {
if (oldEncPos != encoderPos) { // Überprüfen, ob sich die Encoder-Position geändert hat
// lcd.setCursor(0,0); // Text soll beim ersten Zeichen in der ersten Reihe beginnen..
lcd.clear(); // Anzeige löschen
lcd.print(encoderPos); // Encoder Position wird auf dem LCD-Display angezeigt
oldEncPos = encoderPos;
}
int btnState = digitalRead(encoderButtonPin); // Überprüfen des Encoder-Tasters
if (btnState == LOW && millis() - lastButtonPress > 50) { // " " " "
Anwendung(); // Subroutine Anwendung
encoderPos = 0; // encoderPos wird auf 0 gesetzt, wenn Encoder-Taster gedrückt wird
lastButtonPress = millis(); //
}
delay(1); //
}
// ------------------------------------------------------------------------------------------------------------------------------------
void PinA() { // Subroutine PinA()
bool stateA = digitalRead(pinA);
bool stateB = digitalRead(pinB);
if (stateA != stateB) {
if (stateA) {
encoderPos = (encoderPos + 1) % 20;
} else {
encoderPos = (encoderPos - 1 + 20) % 20;
}
}
}
void PinB() { // Subroutine PinB()
bool stateA = digitalRead(pinA);
bool stateB = digitalRead(pinB);
if (stateA != stateB) {
if (stateB) {
encoderPos = (encoderPos - 1 + 20) % 20;
} else {
encoderPos = (encoderPos + 1) % 20;
}
}
}
void Anwendung() { // Subroutine Anwendung
if(encoderPos == 9) {
digitalWrite(LED_BUILTIN, LOW);
}
if(encoderPos == 15) {
digitalWrite(LED_BUILTIN, HIGH);
}
lcd.clear();
lcd.print(encoderPos);
}