//---Tugas 1 
//Nama : Agus Ari Widayat
#include <LiquidCrystal_I2C.h>
#include <DHT.h>

#define ledM 2
#define ledH 4
#define ledB 5

#define DHTPIN 15     
#define DHTTYPE DHT22   

LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPIN, DHTTYPE);

void setup() {
  Serial.begin(115200);
  dht.begin();
  lcd.init();
  lcd.backlight();
  pinMode(ledM, OUTPUT);
  pinMode(ledH, OUTPUT);
  pinMode(ledB, OUTPUT);
}

void loop() {

//---jeda pembacaan dht22
  delay(2000);

//--baca dan simpan nilai temperature dan humidity
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity(); 

//---Logic jika dht22 tidak terbaca
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    lcd.setCursor(0,0);  lcd.print(F(" Tidak terbaca"));
    return;
  }

//---tampilkan ke LCDI2C
  String print_suhu = "temp: " + String(temperature) + "C";
  String print_humd = "humi: " + String(humidity) + " %";
  lcd.setCursor(0,0);  lcd.print(print_suhu);
  lcd.setCursor(0,1);  lcd.print(print_humd);

//---jika suhu lebih dari 20 maka led biru menyala
  if(temperature < 20){
    warnaLed(0,0,255);
  }

//---jika suhu diantara 20 sampai 30 maka led hijau menyala
  if(temperature > 20 && temperature < 30){
    warnaLed(0,255,0);
  }

//---jika suhu lebih dari 30 maka led merah menyala
  if(temperature > 30){
    warnaLed(255,0,0);
  }
}

//---fungsi memanggil led rgb
void warnaLed(int merah, int hijau,int biru){
analogWrite(ledM,merah);
analogWrite(ledH,hijau);
analogWrite(ledB,biru);
}