#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Rotary Encoder and Switch Pins
#define encoderPinA 2
#define encoderPinB 3
#define switchPin 4
// LCD Setup
LiquidCrystal_I2C lcd(0x27, 16, 2); // Change the address if necessary
// Variables
volatile int encoderValue = 0;
int lastEncoded = 0;
boolean direction = false; // false = CW, true = CCW
boolean switchState = HIGH;
boolean lastSwitchState = HIGH;
void setup() {
// Initialize LCD
lcd.begin(16, 2);
lcd.print("Value: ");
// Set up encoder and switch pins
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(switchPin, INPUT_PULLUP);
// Attach interrupts for the encoder pins
attachInterrupt(digitalPinToInterrupt(encoderPinA), updateEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(encoderPinB), updateEncoder, CHANGE);
}
void loop() {
// Read switch state
switchState = digitalRead(switchPin);
// Check for switch press
if (switchState != lastSwitchState) {
delay(50); // debounce
if (switchState == LOW) {
// Switch is pressed
lcd.clear();
lcd.print("Setting Value");
delay(1000); // Change value or perform action here
lcd.clear();
lcd.print("Value: ");
lcd.print(encoderValue);
}
lastSwitchState = switchState;
}
}
void updateEncoder() {
int MSB = digitalRead(encoderPinA);
int LSB = digitalRead(encoderPinB);
int encoded = (MSB << 1) | LSB;
int sum = (lastEncoded << 2) | encoded;
if (sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) {
direction = true; // CCW
} else if (sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) {
direction = false; // CW
}
if (direction) {
encoderValue--;
} else {
encoderValue++;
}
lcd.setCursor(7, 0);
lcd.print(encoderValue);
lastEncoded = encoded;
}