#include <LiquidCrystal_I2C.h>
#define clk 2
#define dt 3
#define sw 4
int counter=0;
LiquidCrystal_I2C lcd(0x27,16,2);
void setup() {
// put your setup code here, to run once:
lcd.init();
lcd.backlight();
pinMode(clk,INPUT);
pinMode(dt, INPUT);
pinMode(sw, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(clk),readEncoder,FALLING);
}
void readEncoder() {
int dtValue = digitalRead(dt);
if (dtValue == HIGH) {
counter++; // Clockwise
}
if (dtValue == LOW) {
counter--; // Counterclockwise
}
}
int getCounter() {
int result;
noInterrupts();
result = counter;
interrupts();
return result;
}
void resetCounter() {
noInterrupts();
counter = 0;
interrupts();
}
void loop() {
// put your main code here, to run repeatedly:
lcd.setCursor(3, 0);
lcd.print("Counter:");
lcd.setCursor(7, 1);
lcd.print(getCounter());
lcd.print(" ");
if (digitalRead(sw) == LOW) {
resetCounter();
}
}