#include "DHT.h"

#define DHTPIN 2     
#define DHTTYPE DHT22   
#define ledMerah 9
#define ledKuning 10
#define ledBiru 11
#define buzzerPin 8

DHT dht(DHTPIN, DHTTYPE);

#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/FreeSansBold9pt7b.h>
#include <Fonts/Picopixel.h>


Adafruit_SSD1306 display(128, 64, &Wire, -1);


void updateDisplay() {
  display.clearDisplay();
  display.setFont();
  display.setTextColor(1);

  float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);

  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  if(t < 29 ){
    digitalWrite(ledBiru, HIGH);
    digitalWrite(ledMerah, LOW);
    digitalWrite(ledKuning, LOW);
    noTone(buzzerPin);
    display.setCursor(42, 42);
    display.print("SUHU RENDAH");
  }else if ((t >=29 ) && (t <= 35)){
    digitalWrite(ledMerah, LOW);
    digitalWrite(ledKuning, HIGH);
    digitalWrite(ledBiru, LOW);
    noTone(buzzerPin);
    display.setCursor(48, 22);
    display.print("SUHU CUKUP");
  }else if (t > 35){
    digitalWrite(ledMerah, HIGH);
    digitalWrite(ledKuning, LOW);
    digitalWrite(ledBiru, LOW);
    display.setCursor(42, 2);
    display.print("SUHU PANAS");
    tone(buzzerPin, 150);
    delay(1000);
    noTone(buzzerPin);
    delay(1000);
  }

  Serial.print(F("Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.println(F("°F"));

  display.display();
}

void setup() {
  Serial.begin(9600);
  //Serial.println(F("DHTxx test!"));

  dht.begin();
  pinMode(ledMerah, OUTPUT);
  pinMode(ledKuning, OUTPUT);
  pinMode(ledBiru, OUTPUT); 
  pinMode(buzzerPin, OUTPUT);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  updateDisplay();
}

void loop() {
  delay(500);

    digitalWrite(ledMerah, LOW);
    digitalWrite(ledKuning, LOW);
    digitalWrite(ledBiru, LOW);

    updateDisplay();

}