#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

// DHT22 setup
#define DHTPIN 4       // GPIO pin ที่ต่อกับ DATA ของ DHT22
#define DHTTYPE DHT22  // ประเภทของเซนเซอร์
DHT dht(DHTPIN, DHTTYPE);

// OLED setup
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

// LED and Buzzer setup
#define RED_LED_PIN 13
#define BLUE_LED_PIN 12
#define BUZZER_PIN 14

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  Serial.println("DHT22 and OLED with Alarm");

  // Initialize DHT sensor
  dht.begin();

  // Initialize OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println("SSD1306 allocation failed!");
    for (;;);
  }
  display.display();
  delay(2000); // ให้เวลาเริ่มต้นหน้าจอ OLED
  display.clearDisplay();
  display.setTextColor(WHITE);

  // Setup LED and Buzzer pins
  pinMode(RED_LED_PIN, OUTPUT);
  pinMode(BLUE_LED_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  delay(2000); // DHT22 ต้องการเวลาในการอ่านค่า

  // Read temperature and humidity
  float t = dht.readTemperature();
  float h = dht.readHumidity();

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

  // Clear OLED display
  display.clearDisplay();

  // Display temperature on OLED
  display.setTextSize(1);
  display.setCursor(0, 0);
  display.print("Temperature: ");
  display.setTextSize(2);
  display.setCursor(0, 10);
  display.print(t);
  display.print(" ");
  display.setTextSize(1);
  display.cp437(true); // Use degrees symbol
  display.write(167);
  display.setTextSize(2);
  display.print("C");

  // Display humidity on OLED
  display.setTextSize(1);
  display.setCursor(0, 35);
  display.print("Humidity: ");
  display.setTextSize(2);
  display.setCursor(0, 45);
  display.print(h);
  display.print(" %");

  display.display();

  // Alarm logic
  if (t > 50.0) {
    digitalWrite(RED_LED_PIN, HIGH);
    digitalWrite(BLUE_LED_PIN, LOW);
    tone(BUZZER_PIN, 1000); // เปิด Buzzer
    Serial.println("Warning: Temperature too high!");
  } else if (t < 0.0) {
    digitalWrite(RED_LED_PIN, LOW);
    digitalWrite(BLUE_LED_PIN, HIGH);
    tone(BUZZER_PIN, 500); // เปิด Buzzer
    Serial.println("Warning: Temperature too low!");
  } else {
    digitalWrite(RED_LED_PIN, LOW);
    digitalWrite(BLUE_LED_PIN, LOW);
    noTone(BUZZER_PIN); // ปิด Buzzer
    Serial.println("Temperature is normal.");
  }
}