#include #include LiquidCrystal_I2C oLcd(0x3F, 16, 2); // Rotary Encoder Inputs #define CLK PB4 #define DT PB5 #define BTN PA15 int counter = 0; int currentStateCLK; int lastStateCLK; String currentDir = ""; unsigned long lastButtonPress = 0; void setup() { // Set encoder pins as inputs pinMode(CLK, INPUT); pinMode(DT, INPUT); pinMode(BTN, INPUT_PULLUP); // Read the initial state of CLK lastStateCLK = digitalRead(CLK); oLcd.init(); oLcd.backlight(); oLcd.setCursor(0, 0); attachInterrupt(CLK, updateEncoder, CHANGE); attachInterrupt(DT, updateEncoder, CHANGE); attachInterrupt(BTN, updateBtnPressed, CHANGE); } void loop() { } void updateEncoder(){ // Read the current state of CLK currentStateCLK = digitalRead(CLK); // If last and current state of CLK are different, then pulse occurred // React to only 1 state change to avoid double count if (currentStateCLK != lastStateCLK && currentStateCLK == 1){ // If the DT state is different than the CLK state then // the encoder is rotating CCW so decrement if (digitalRead(DT) != currentStateCLK) { counter --; currentDir ="CCW"; } else { // Encoder is rotating CW so increment counter ++; currentDir ="CW"; } oLcd.clear(); oLcd.print("Direction: "); oLcd.print(currentDir); oLcd.setCursor(0, 1); oLcd.print("Counter: "); oLcd.print(counter); } // Remember last CLK state lastStateCLK = currentStateCLK; } void updateBtnPressed() { int btnState = digitalRead(BTN); if (btnState == LOW) { if (millis() - lastButtonPress > 50) { oLcd.clear(); oLcd.print("Button pressed!"); } lastButtonPress = millis(); } }