#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "DHTesp.h"

#define TINGGI_LAYAR 64 // Tinggi layar OLED yang digunakan
#define LEBAR_LAYAR 128 // Lebar layar OLED yang digunakan

Adafruit_SSD1306 display(LEBAR_LAYAR, TINGGI_LAYAR, &Wire, -1);
const int LED_PIN = 13;
const int DHT_PIN = 15;
DHTesp dhtSensor;

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

  // Memastikan OLED dapat berjalan atau tidak
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }

  // Setup DHT sensor
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  display.clearDisplay(); // membersihkan tampilan
  display.setTextColor(WHITE); //warna OLED (putih)

  //Setup LED
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  // Read temperature and humidity from DHT sensor
  TempAndHumidity data = dhtSensor.getTempAndHumidity();

  // Display temperature and humidity on OLED
  display.clearDisplay(); // Clear the previous display
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("Temp: " + String(data.temperature, 2) + "C");
  display.setCursor(0, 20);
  display.print("Humidity: " + String(data.humidity, 1) + "%");
  display.display(); // Update the OLED display

  // Print temperature and humidity to Serial for debugging
  Serial.println("Temp: " + String(data.temperature, 2) + "C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");

  digitalWrite(LED_PIN, HIGH);
  delay(2000); // Wait for a new reading from the sensor (DHT22 has ~0.5Hz sample rate)
  digitalWrite(LED_PIN, LOW);
}