#include <Wire.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);

#define ntc 35
#define LDR_A 4
#define LDR_D 2

#define LED_GREEN 14
#define LED_BLUE 19

int ana_val;
int LDR_Aval;
int LDR_Dval;


const float BETA = 3950;

const float GAMMA = 0.7;
const float RL10 = 50;

void setup() {
  pinMode(ntc, INPUT);
  pinMode(LDR_A, INPUT);
  pinMode(LDR_D, INPUT_PULLUP);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);

  Serial.begin(9600);


  lcd.init();
  lcd.backlight();
  lcd.setCursor(2, 0);
  lcd.print("Tamp");
  lcd.setCursor(12, 0);
  lcd.print("Light");


  lcd.setCursor(0, 3);
  lcd.print("Air>");
  lcd.setCursor(11, 3);
  lcd.print("Lamp>");
  lcd.setCursor(8, 0);
  lcd.print("|");
  lcd.setCursor(8, 1);
  lcd.print("|");
  lcd.setCursor(8, 2);
  lcd.print("|");
  lcd.setCursor(8, 3);
  lcd.print("|");
}


void loop() {

  ana_val = analogRead(ntc);
  float celsius = 1 / (log(1 / (4095. / ana_val - 1)) / BETA + 1.0 / 298.15) - 273.15;

  LDR_Aval = analogRead(LDR_A);
  float voltage = LDR_Aval / 4095. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5.0);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  LDR_Dval = digitalRead(LDR_D);

  lcd.setCursor(0, 1);
  lcd.print(String(celsius, 2) + " C ");

  lcd.setCursor(10, 1);
  lcd.print(String(lux, 2)+(" "));
  lcd.setCursor(17, 1);
  lcd.print("Lux");

  if (celsius >= 30) {
    digitalWrite(LED_GREEN, HIGH);
    lcd.setCursor(5, 3);
    lcd.print("ON ");
  }
  if (celsius <= 28) {
    digitalWrite(LED_GREEN, LOW);
    lcd.setCursor(5, 3);
    lcd.print("OFF");
  }

  if (lux >= 50) {
    digitalWrite(LED_BLUE, LOW);
    lcd.setCursor(17, 3);
    lcd.print("OFF");
  } else {
    digitalWrite(LED_BLUE, HIGH);
    lcd.setCursor(17, 3);
    lcd.print("ON ");
  }

  Serial.print("NTC = ");
  Serial.print(ana_val);
  Serial.print("   : Celsius = ");
  Serial.print(celsius);
  Serial.print("   : LDR_A = ");
  Serial.print(LDR_Aval);
  Serial.print("   : lux = ");
  Serial.print(lux);
  Serial.print("   : LDR_D = ");
  Serial.println(LDR_Dval);
  delay(250);

}