#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <DHT.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

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

// DHT22 sensor configuration
#define DHT_PIN 2
#define DHT_TYPE DHT22
DHT dht(DHT_PIN, DHT_TYPE);

// WiFi credentials
char auth[] = "GWAYpKY2LqxEph9zB8-v9PeWneijuT6w";
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

// Blynk virtual pin for temperature and humidity display
#define VIRTUAL_PIN_TEMPERATURE V1
#define VIRTUAL_PIN_HUMIDITY V2

void setup() {
  // Initialize the OLED display
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
display.setTextSize(1.5);

  // Initialize the DHT sensor
  dht.begin();

  // Connect to Wi-Fi
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  // Initialize Blynk
  Blynk.begin(auth, ssid, pass);
}

void loop() {
  Blynk.run();
  display.clearDisplay();

  // Read temperature and humidity from DHT22
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

// Display temperature and humidity on the OLED display
  display.setCursor(0, 0);
  display.print("Hi! Hitarth           ");
  display.print("Temperature:");
  display.print(temperature);
  display.println(" *C ");

  display.setCursor(0, 16);
  display.print(" Humidity: ");
  display.print(humidity);
  display.println(" % ");
  display.setCursor(0, 32);
  display.display();

  // Send temperature and humidity data to Blynk
  Blynk.virtualWrite(VIRTUAL_PIN_TEMPERATURE, temperature);
  Blynk.virtualWrite(VIRTUAL_PIN_HUMIDITY, humidity);

  delay(2000);
}