#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// LCD setup
LiquidCrystal_I2C lcd(0x27, 20, 4); // I2C address 0x27, 20 columns, 4 rows
// Rotary Encoder pins
#define CLK 4
#define DT 3
#define SW 2
// RGB LED pins
#define RED_PIN 5
#define GREEN_PIN 6
#define BLUE_PIN 9
int led_onoff = 1;
static int oldCLK = LOW;
static int oldDT = LOW;
int RED, GREEN, BLUE;
int INTERVEL, DURATION;
int mr, mg, mb, mi, md;
char buf[20];
int mode = 0;
int menu = 0;
int encoderValue = 0;
int lastCLK = HIGH;
void setup() {
// Initialize the LCD
lcd.begin(20, 4);
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Encoder Value:");
// Rotary encoder setup
pinMode(CLK, INPUT);
pinMode(DT, INPUT);
pinMode(SW, INPUT_PULLUP); // Button with internal pull-up resistor
// RGB LED setup
pinMode(RED_PIN, OUTPUT);
pinMode(GREEN_PIN, OUTPUT);
pinMode(BLUE_PIN, OUTPUT);
// Initial RGB LED color
setLEDColor(0, 0, 255); // Start with Blue
}
void loop() {
// Read the rotary encoder
int currentCLK = digitalRead(CLK);
if (currentCLK != lastCLK) {
if (digitalRead(DT) != currentCLK) {
encoderValue++; // Clockwise rotation
} else {
encoderValue--; // Counter-clockwise rotation
}
updateLCD();
updateLED();
}
lastCLK = currentCLK;
// Reset value with the button
if (digitalRead(SW) == LOW) {
encoderValue = 0;
updateLCD();
updateLED();
delay(200); // Debounce delay
}
}
void updateLCD() {
lcd.setCursor(0, 1);
lcd.print("Value: ");
lcd.print(encoderValue);
lcd.print(" "); // Clear remaining characters
}
void updateLED() {
// Change RGB LED color based on encoder value
int red = map(encoderValue, 0, 100, 0, 255); // Map value to red intensity
int green = map(encoderValue, 100, 200, 0, 255); // Map value to green intensity
int blue = map(encoderValue, 200, 300, 0, 255); // Map value to blue intensity
setLEDColor(red, green, blue);
}
void setLEDColor(int red, int green, int blue) {
analogWrite(RED_PIN, constrain(red, 0, 255));
analogWrite(GREEN_PIN, constrain(green, 0, 255));
analogWrite(BLUE_PIN, constrain(blue, 0, 255));
}