#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Encoder.h>
#define LCD_ADDRESS 0x27
#define NUM_OPTIONS 3
const char* options[NUM_OPTIONS] = {
"Optiunea 1",
"Optiunea 2",
"Optiunea 3"
};
#define ENCODER_PIN_A 3
#define ENCODER_PIN_B 2
#define ENCODER_BUTTON_PIN 4
LiquidCrystal_I2C lcd(LCD_ADDRESS, 20, 4);
Encoder encoder(ENCODER_PIN_A, ENCODER_PIN_B);
int currentOption = 0;
int old_val = 0;
bool dir_CW = false;
int newPosition = 0;
void setup() {
lcd.init();
lcd.backlight();
lcd.setCursor(7, 0);
lcd.print("MENIU");
for (int i = 0; i < NUM_OPTIONS; ++i) {
lcd.setCursor(1, i + 1);
lcd.print(options[i]);
}
lcd.setCursor(0, 1);
lcd.print(">");
pinMode(ENCODER_BUTTON_PIN, INPUT_PULLUP);
}
bool rotary_move() {
static bool am_new_val = false;
static uint32_t timeD;
int new_val = encoder.read();
if (new_val != old_val) {
dir_CW = new_val > old_val;
old_val = new_val;
timeD = millis();
am_new_val = true;
return false;
} else if (am_new_val && millis() - timeD > 50) {
am_new_val = false;
return true;
}
return false;
}
void loop() {
if (rotary_move()) {
newPosition += dir_CW ? +1 : -1;
if (newPosition > NUM_OPTIONS - 1) {
newPosition = NUM_OPTIONS - 1;
} else if (newPosition < 0) {
newPosition = 0;
}
// Limit the newPosition to be within 0 and NUM_OPTIONS - 1
newPosition = constrain(newPosition, 0, NUM_OPTIONS - 1);
lcd.setCursor(0, currentOption + 1);
lcd.print(" ");
lcd.setCursor(0, newPosition + 1);
lcd.print(">");
currentOption = newPosition;
}
}