#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> 
#include <LiquidCrystal_I2C.h>
HTTPClient http;
LiquidCrystal_I2C lcd(0x27,16,2);  
void setup() {
  Serial.begin(9600);
  Serial.print("Connecting to WiFi");
  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print(".");
  }
  Serial.println(" Connected!");
  lcd.init();
  lcd.backlight();
}
void loop() {
  if ((WiFi.status() == WL_CONNECTED)) {
    HTTPClient http;
    http.begin("https://api.openweathermap.org/data/2.5/weather?id=1562693&appid=e6bd7bec9854fa8f51b3d32069925e13");
    int httpCode = http.GET();
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      // Tạo một đối tượng DynamicJsonDocument để phân tích JSON
      DynamicJsonDocument doc(1024);
      deserializeJson(doc, payload);
      // Lấy nhiệt độ và độ ẩm từ JSON
      float temperature = doc["main"]["temp"].as<float>() - 273.15;  
      int humidity = doc["main"]["humidity"].as<int>();
      // In ra Serial
      Serial.print("Nhiệt độ: ");
      Serial.print(temperature);
      Serial.println("°C");
      Serial.print("Độ ẩm: ");
      Serial.print(humidity);
      Serial.println("%");
      //hiển thị ra lcd
      lcd.clear();                           
      lcd.setCursor(0,0);                    
      lcd.print("Nhiet do: ");  
      lcd.print(temperature);
      lcd.print("C");
      lcd.setCursor(0,1);                     
      lcd.print("Do am: ");
      lcd.print(humidity);
      lcd.print("%");
    }
    else {
      Serial.println("Error on HTTP request");
    }
    http.end();
  }
  delay(10000);
}