#include <WiFi.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
void setup() {
lcd.init();
lcd.backlight();
Serial.begin(115200);
Serial.println("Hello, ESP32!");
WiFi.begin("Wokwi-GUEST", "");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
}
void getWeatherInfo (String location) {
String api_key = "9396f69fee320a0014ac3fa7ab35381d";
String api = "http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=" + api_key;
String output = "";
WiFiClient client;
HTTPClient http;
if (http.begin(client, api)) {
int httpCode = http.GET();
if (httpCode > 0) {
Serial.print("http code");
Serial.println(httpCode);
if (httpCode == HTTP_CODE_OK) {
output = http.getString();
Serial.print(output);
showInfoLCD(lcd, output);
}
} else {
Serial.println(httpCode);
Serial.println("Failed");
}
http.end();
} else {
Serial.println("unable to connect");
}
}
void showInfoLCD(LiquidCrystal_I2C lcd, String input) {
lcd.clear();
int lonPosStart1 = input.indexOf("\"pressure\":") + 11;
int lonPosEnd1 = input.indexOf(",", lonPosStart1);
int lonPosStart = input.indexOf("\"temp\":") + 7;
int lonPosEnd = input.indexOf(",", lonPosStart );
String lon1 = input.substring(lonPosStart1, lonPosEnd1);
String lon = input.substring(lonPosStart, lonPosEnd);
int temp = lon.toInt() - 273;
int pressure = lon1.toInt();
lcd.setCursor(0,0);
lcd.print("temp: ");
lcd.print(temp);
lcd.setCursor(0,1);
lcd.print("pressure: ");
lcd.print(pressure);
}
void loop() {
getWeatherInfo("Hanoi");
delay(10000);
}