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

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

#define DHTPIN 13
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

#define RAIN_ANALOG 34
#define RAIN_DIGITAL 16

const int redPin = 14;
const int greenPin = 27;
const int bluePin = 26;

int rainValue;
String weatherCondition;
int r, g, b; // Khai báo biến toàn cục

void setup() {
  Serial.begin(9600);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(RAIN_ANALOG, INPUT);
  pinMode(RAIN_DIGITAL, INPUT);
  analogReadResolution(10);

  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  Serial.println("OLED display connected successfully");
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println(F("Weather Analysis"));
  display.display();
  delay(2000);

  dht.begin();
}

void loop() {
  float humidity = dht.readHumidity();
  float temperature = dht.readTemperature();
  bool isRaining = !digitalRead(RAIN_DIGITAL);
  rainValue = analogRead(RAIN_ANALOG);

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

  if (isRaining) { 
    if (temperature < 36) {
      if (temperature < 28 && humidity > 98) {
        weatherCondition = "Suong mu";
        r = 255;
        g = 80;
        b = 5;
      } else if (humidity >= 87 && humidity < 98) {
        weatherCondition = "Mua";
        r = 205;
        g = 90;
        b = 20;
      } else {
        weatherCondition = "Kho";
        r = 255;
        g = 255;
        b = 255;
      }
    } else {
      weatherCondition = "Kho";
      r = 255;
      g = 255;
      b = 255;
    }
  } else { 
    weatherCondition = "Kho";
    r = 255;
    g = 255;
    b = 255;
  }

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print(F("Thoi tiet: "));
  display.println(weatherCondition);
  display.print(F("Nhiet do: "));
  display.print(temperature);
  display.println(" C");
  display.print(F("Do am: "));
  display.print(humidity);
  display.println(" %");
  display.print(F("Co mua: "));
  display.println(isRaining ? "Co" : "Khong");
  display.display();

  Serial.println(F("Thời tiết: "));
  Serial.println(weatherCondition);
  Serial.print(F("Nhiệt độ: "));
  Serial.print(temperature);
  Serial.println(" C");
  Serial.print(F("Độ ẩm: "));
  Serial.print(humidity);
  Serial.println(" %");
  Serial.print(F("Có mưa: "));
  Serial.println(isRaining ? "Co" : "Khong");
  Serial.println();

  analogWrite(redPin, r);
  analogWrite(greenPin, g);
  analogWrite(bluePin, b);

  delay(2000);
}
rain-sensorBreakout