#include <Wire.h>
#include <LiquidCrystal_I2C.h>

const int analogInPin = A0;
const int Red = 13;
const int Yellow = 12;
const int Green = 11;

LiquidCrystal_I2C lcd(0x27, 16, 2);

void turnOnLEDs(bool green, bool yellow, bool red) {
  digitalWrite(Green, green ? HIGH : LOW);
  digitalWrite(Yellow, yellow ? HIGH : LOW);
  digitalWrite(Red, red ? HIGH : LOW);
}

void blinkAllLEDs() {
  static unsigned long previousMillis = 0;
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= 200) {
    previousMillis = currentMillis;

    digitalWrite(Green, !digitalRead(Green));
    digitalWrite(Yellow, !digitalRead(Yellow));
    digitalWrite(Red, !digitalRead(Red));
  }
}

void updateLEDs(int mappedValue) {
  if (mappedValue >= 0 && mappedValue <= 33) {
    turnOnLEDs(true, false, false);
  } else if (mappedValue > 33 && mappedValue <= 66) {
    turnOnLEDs(true, true, false);
  } else if (mappedValue > 66 && mappedValue <= 99) {
    turnOnLEDs(true, true, true);
  } else {
    blinkAllLEDs();
  }
}

void displayOnLCD(int mappedValue, int &previousMappedValue) {
  lcd.setCursor(0, 0);
  lcd.print(String(mappedValue) + "%");

  if (mappedValue != previousMappedValue) {
    lcd.clear();
    previousMappedValue = mappedValue;
  }
}

void setup() {
  pinMode(Red, OUTPUT);
  pinMode(Yellow, OUTPUT);
  pinMode(Green, OUTPUT);

  lcd.init();
  lcd.backlight();
  lcd.clear();
}

void loop() {
  int analogValue = analogRead(analogInPin);
  int mappedValue = map(analogValue, 0, 1023, 0, 100);
  static int previousMappedValue = -1;

  updateLEDs(mappedValue);
  displayOnLCD(mappedValue, previousMappedValue);
}