#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <EEPROM.h>
#define PIN_CLK 2 // Interruption INT0
#define PIN_DT 3
#define PIN_SW 4
LiquidCrystal_I2C lcd(0x27, 16, 2);
volatile int rotation = 0; // +1 ou -1 selon le sens
int valeurs[3] = {0, 0, 0};
int indexActif = 0;
const char* labels[3] = {"A", "B", "C"};
unsigned long appuiDebut = 0;
bool appuiLongDetecte = false;
void setup() {
lcd.init();
lcd.backlight();
pinMode(PIN_CLK, INPUT_PULLUP);
pinMode(PIN_DT, INPUT_PULLUP);
pinMode(PIN_SW, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(PIN_CLK), onEncoderTurn, FALLING);
// Charger depuis l'EEPROM
for (int i = 0; i < 3; i++) {
int v = EEPROM.read(i);
valeurs[i] = constrain(v, 0, 255);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Chargement OK");
delay(1000);
lcd.clear();
}
void loop() {
// Appliquer la rotation détectée
noInterrupts();
int rot = rotation;
rotation = 0;
interrupts();
if (rot != 0) {
valeurs[indexActif] += rot;
if (valeurs[indexActif] > 255) valeurs[indexActif] = 255;
if (valeurs[indexActif] < 0) valeurs[indexActif] = 0;
}
// Gestion bouton
bool bouton = !digitalRead(PIN_SW);
if (bouton) {
if (appuiDebut == 0) {
appuiDebut = millis();
} else if (!appuiLongDetecte && millis() - appuiDebut > 1500) {
appuiLongDetecte = true;
// Sauvegarde
for (int i = 0; i < 3; i++) {
EEPROM.update(i, valeurs[i]);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Valeurs sauvees!");
delay(2000);
lcd.clear();
}
} else {
if (appuiDebut != 0 && !appuiLongDetecte) {
indexActif = (indexActif + 1) % 3;
}
appuiDebut = 0;
appuiLongDetecte = false;
}
// Affichage
char ligne1[17];
snprintf(ligne1, sizeof(ligne1), "%s%03d %s%03d %s%03d",
labels[0], valeurs[0],
labels[1], valeurs[1],
labels[2], valeurs[2]);
lcd.setCursor(0, 0);
lcd.print(ligne1);
int positions[3] = {1, 6, 11};
lcd.setCursor(0, 1);
lcd.print(" ");
lcd.setCursor(positions[indexActif] + 1, 1);
lcd.print("^");
delay(10);
}
// ---------- ISR pour l’encodeur ----------
void onEncoderTurn() {
if (digitalRead(PIN_DT) != digitalRead(PIN_CLK)) {
rotation=rotation + 5;
} else {
rotation = rotation - 5;
}
}