#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire);

#define pinLEDMerah 8
#define pinLEDKuning 7
#define pinLEDBiru 6
#define pinBuzz 3

#include "DHTesp.h"

const int DHT_PIN = 4;

DHTesp dhtSensor;

void setup() {
  Serial.begin(9600);

  pinMode(pinLEDMerah, OUTPUT);
  pinMode(pinLEDKuning, OUTPUT);
  pinMode(pinLEDBiru, OUTPUT);
  pinMode(pinBuzz, OUTPUT);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { 
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); 
  }

  display.clearDisplay();
  display.setTextColor(WHITE);
  display.setTextSize(1);
  display.setCursor(20,20);  display.println(F("WELKOM"));
  display.display(); //tampilkan data
 

}

void loop() {  
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  Serial.println("Temp: " + String(data.temperature, 2) + "°C");
  
  if (data.temperature < 29) {
    // air rendah
    digitalWrite(pinLEDMerah, LOW);
    digitalWrite(pinLEDKuning, LOW);
    digitalWrite(pinLEDBiru, HIGH); 
    noTone(pinBuzz);   

    Serial.println("SUHU RENDAH");
    display.clearDisplay();
    display.setCursor(20,20);  display.println(F("SUHU RENDAH"));
    display.setCursor(20,10);  display.println("Temp: " + String(data.temperature, 2) + " C");
    display.display();
  } else if (data.temperature >= 29 && data.temperature <= 35) {
    // air sedang
    digitalWrite(pinLEDMerah, LOW);
    digitalWrite(pinLEDKuning, HIGH);
    digitalWrite(pinLEDBiru, LOW); 
    noTone(pinBuzz);      

    Serial.println("SUHU SEDANG");
    display.clearDisplay();
    display.setCursor(20,20);  display.println(F("SUHU SEDANG"));
    display.setCursor(20,10);  display.println("Temp: " + String(data.temperature, 2) + " C");
    display.display();
  } else if (data.temperature > 35) {
    // air rendah
    digitalWrite(pinLEDMerah, HIGH);
    digitalWrite(pinLEDKuning, LOW);
    digitalWrite(pinLEDBiru, LOW);
    tone(pinBuzz, 100, 1000);   
    Serial.println("SUHU PANAS");
    display.clearDisplay();
    display.setCursor(20,20);  display.println(F("SUHU PANAS"));
    display.setCursor(20,10);  display.println("Temp: " + String(data.temperature, 2) + " C");
    display.display();
  }  
  delay(1000);
}