#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include "time.h"
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
String URL = "http://api.openweathermap.org/data/2.5/weather?";
String ApiKey = "6c68e32516db69e49b9df906131ee2bf";
String lat = "20.36064679936554";
String lon = "106.14353154454663";
struct tm timeinfo;
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 25200;
const int daylightOffset_sec = 25200;//GMT+7
void setup() {
tft.begin();
tft.fillScreen(ILI9341_WHITE);
//connecting to a WiFi network
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!");
// Init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
printLocalTime();
tft.begin();
tft.fillScreen(ILI9341_WHITE);
}
void loop() {
printLocalTemphumi();
printLocalTime();
}
void printLocalTemphumi(){
// wait for WiFi connection
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
//Set HTTP Request Final URL with Location and API key information
http.begin(URL + "lat=" + lat + "&lon=" + lon + "&units=metric&appid=" + ApiKey);
// start connection and send HTTP Request
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
//Read Data as a JSON string
String JSON_Data = http.getString();
Serial.println(JSON_Data);
//Retrieve some information about the weather from the JSON format
DynamicJsonDocument doc(2048);
deserializeJson(doc, JSON_Data);
JsonObject obj = doc.as<JsonObject>();
//Display the Current Weather Info
const char* description = obj["weather"][0]["description"].as<const char*>();
const float temp = obj["main"]["temp"].as<float>();
const float humidity = obj["main"]["humidity"].as<float>();
tft.setCursor(80, 150);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.println(temp);
tft.setCursor(160, 150);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.println(" C");
tft.setCursor(80, 200);
tft.setTextColor(ILI9341_BLUE);
tft.setTextSize(3);
tft.println(humidity);
tft.setCursor(160, 200);
tft.setTextColor(ILI9341_BLUE);
tft.setTextSize(3);
tft.println(" %");
}
http.end();
}
delay(10000);
}
void printLocalTime(){
if(!getLocalTime(&timeinfo)){
return;
}
tft.setCursor(80, 90);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.println(&timeinfo, "%H:%M");
tft.setCursor(40, 50);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.println(&timeinfo, "%d/%m/%Y");
tft.setCursor(10, 10);
tft.setTextColor(ILI9341_BLACK);
tft.setTextSize(3);
tft.println(&timeinfo, "%A");
}