#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 20, 4);

#define ENCODER_CLK 2
#define ENCODER_DT 3
#define ENCODER_SW 4

volatile int counter = 0; // Make counter variable volatile

void setup() {
  lcd.init();
  lcd.backlight();

  // Initialize encoder pins
  pinMode(ENCODER_CLK, INPUT);
  pinMode(ENCODER_DT, INPUT);
  pinMode(ENCODER_SW, INPUT_PULLUP);

  // Use CHANGE interrupt for both rising and falling edges
  attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, CHANGE);
}

void readEncoder() {
  int clkValue = digitalRead(ENCODER_CLK);
  int dtValue = digitalRead(ENCODER_DT);

  if (clkValue == HIGH) {
    if (dtValue == LOW) {
      counter++; // Clockwise
    } else {
      counter--; // Counterclockwise
    }
  } else {
    if (dtValue == HIGH) {
      counter++; // Clockwise
    } else {
      counter--; // Counterclockwise
    }
  }
}

int getCounter() {
  int result;
  noInterrupts();
  result = counter;
  interrupts();
  return result;
}

void resetCounter() {
  noInterrupts();
  counter = 0;
  interrupts();
}

void loop() {
  lcd.setCursor(3, 0);
  lcd.print("Counter:");
  lcd.setCursor(7, 1);
  lcd.print(getCounter());
  lcd.print("    ");

  if (digitalRead(ENCODER_SW) == LOW) {
    resetCounter();
    delay(500); // Debounce delay to avoid multiple resets
  }
}