#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define ENC_A 2
#define ENC_B 3
#define ENC_SW 4
volatile int encoderPos = 0;
volatile bool lastA = HIGH;
void encoderISR() {
bool A = digitalRead(ENC_A);
bool B = digitalRead(ENC_B);
if (A != lastA) {
if (B != A) {
encoderPos++;
} else {
encoderPos--;
}
encoderPos = constrain(encoderPos, 0, 100);
lastA = A;
}
}
void setup() {
pinMode(ENC_A, INPUT_PULLUP);
pinMode(ENC_B, INPUT_PULLUP);
pinMode(ENC_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENC_A), encoderISR, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_B), encoderISR, CHANGE);
lcd.init();
lcd.backlight();
}
void loop() {
static int lastDisplayed = -1;
static bool lastBtnState = HIGH;
bool btnState = digitalRead(ENC_SW);
if (btnState == LOW && lastBtnState == HIGH) {
noInterrupts();
encoderPos = 50;
interrupts();
delay(50);
}
lastBtnState = btnState;
noInterrupts();
int currentPos = encoderPos;
interrupts();
if (currentPos != lastDisplayed) {
lcd.setCursor(0, 0);
lcd.print("Wartosc:");
char buf[8];
sprintf(buf, "%3d/100", currentPos); // zawsze 7 znaków: "100/100", " 99/100", " 1/100"
lcd.setCursor(9, 0);
lcd.print(buf);
lastDisplayed = currentPos;
}
}