#include <LiquidCrystal_I2C.h>

// Define the beta value of the thermistor, typically provided in the datasheet
#define Led_Pin 4                 // LED pin 
#define Tem_sensor 35             // Temperature sensor connection
#define I2C_ADDR    0x27          // I2C address of the LCD
#define LCD_COLUMNS 16            // Number of colunms in the LCD
#define LCD_LINES   2             // Number of rows
const float ADC_coef = 4;         // ADC coefficient of ESP32
unsigned long blinking_time[5] = {1000, 2000, 3000, 4000, 5000};
unsigned long Previous_time = 0;
bool led_on = false;

LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);

void setup() {
  // put your setup code here, to run once:
  lcd.init();
  lcd.backlight();
  Serial.begin(115200);
  pinMode(Led_Pin, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  int analogValue = analogRead(Tem_sensor) / ADC_coef;
  float temp_Cel = 1 / (log(1 / (1023. / analogValue - 1)) / 3950 + 1.0 / 298.15) - 273.15;
  float temp_Fah = temp_Cel * 1.8 + 32;

  if (temp_Cel > 70)
  {
    digitalWrite(Led_Pin, HIGH);
  }
  else if (temp_Cel >= 65 && temp_Cel < 66)
  {
    unsigned long now = millis();
    if ((now - Previous_time)>=blinking_time[4])
    {
    led_on = !led_on;
    digitalWrite(Led_Pin, led_on);
    Previous_time = now;
    }

  }
  else if (temp_Cel >= 66 && temp_Cel < 67)
  {
    unsigned long now = millis();
    if ((now - Previous_time)>=blinking_time[3])
    {
    led_on = !led_on;
    digitalWrite(Led_Pin, led_on);
    Previous_time = now;
    }

  }
  else if (temp_Cel >= 67 && temp_Cel < 68)
  {
    unsigned long now = millis();
    if ((now - Previous_time)>=blinking_time[2])
    {
    led_on = !led_on;
    digitalWrite(Led_Pin, led_on);
    Previous_time = now;
    }

  }
  else if (temp_Cel >= 68 && temp_Cel < 69)
  {
    unsigned long now = millis();
    if ((now - Previous_time)>=blinking_time[1])
    {
    led_on = !led_on;
    digitalWrite(Led_Pin, led_on);
    Previous_time = now;
    }

  }
  else if (temp_Cel >= 69 && temp_Cel < 70)
  {
    unsigned long now = millis();
    if ((now - Previous_time)>=blinking_time[0])
    {
    led_on = !led_on;
    digitalWrite(Led_Pin, led_on);
    Previous_time = now;
    }

  }

  else
    {
      led_on =false;
      digitalWrite(Led_Pin, led_on);
    }


  // Display
  lcd.setCursor(0, 0);
  lcd.print("Cel: ");
  lcd.print(temp_Cel);
  lcd.setCursor(0, 1);
  lcd.print("Fah: ");
  lcd.print(temp_Fah);
  delay(1000);
}