#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 lastBlink = 0;
unsigned long currentTime = 0;
bool led_on = false;
int32_t  interval = 0;


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() {
  // Determine the interval for blinking yellow engine sign in case of high motor temps
  delay(50);
  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;
  digitalWrite(Led_Pin, LOW);

  switch ((int)temp_Cel)
  {
    case 25: //130
      interval = 2500;
      break;
    case 26: //131
      interval = 2000;
      break;
    case 27: //132
      interval = 1500;
      break;
    case 28: //133
      interval = 1000;
      break;
    case 29: //134
      interval = 500;
      break;
    case 30: //135
    case 31: //136
    case 32: //137
    case 33: //138
    case 34: //139
    case 35: //140
      interval = 0;
      break;
    default:
      interval = -1;
      break;
  }

  // If temperature is above 130 then blink in intervals or light up continuously
  if (interval != -1) {
    currentTime = millis();
    if (currentTime >= lastBlink + interval) {

      digitalWrite(Led_Pin, HIGH);
      lastBlink = currentTime;
    }
  }
  lcd.setCursor(0, 0);
  lcd.print("Cel: ");
  lcd.print(temp_Cel);
  lcd.setCursor(0, 1);
  lcd.print("Fah: ");
  lcd.print(temp_Fah);
}