/*
Rui Santos
Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-open-weather-map-thingspeak-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*/
#include <Arduino.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>
#include <Wire.h>
#include <Adafruit_GFX.h> //OLEDのGFXライブラリ
#include <Adafruit_SSD1306.h> //OLEDのライブラリ
#include "NTPClient.h"
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//OLEDの初期設定
Adafruit_SSD1306 display(128, 64, &Wire, -1);
// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "";
// Example:
//String openWeatherMapApiKey = "bd939aa3d23ff33d3c8f5dd1dd435";
// Replace with your country code and city
String city = "Morioka";
String countryCode = "JP";
// THE DEFAULT TIMER IS SET TO 10 SECONDS FOR TESTING PURPOSES
// For a final application, check the API call limits per hour/minute to avoid getting blocked/banned
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 10 seconds (10000)
unsigned long timerDelay = 10000;
String jsonBuffer;
WiFiUDP udp;
NTPClient ntp(udp, "ntp.nict.jp", 32400, 60000);
// udp, ServerName, timeOffset, updateInterval
void setup() {
Serial.begin(115200);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
configTime(9 * 3600L, 0, "ntp.nict.jp", "time.google.com", "ntp.jst.mfeed.ad.jp");//NTPの設定
}
ntp.begin();
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
Serial.println("Timer set to 10 seconds (timerDelay variable), it will take 10 seconds before publishing the first reading.");
//OLEDの初期化
display.clearDisplay();
display.setTextColor(WHITE);
}
void loop() {
// Send an HTTP GET request
if ((millis() - lastTime) > timerDelay) {
// Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;
jsonBuffer = httpGETRequest(serverPath.c_str());
Serial.println(jsonBuffer);
JSONVar myObject = JSON.parse(jsonBuffer);
// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
Serial.println("Parsing input failed!");
return;
}
ntp.update();
String formattedTime = ntp.getFormattedTime(); // hh:mm:ss
double tempc = myObject["main"]["temp"];
int prs = myObject["main"]["pressure"];
int hum = myObject["main"]["humidity"];
double speed = myObject["wind"]["speed"];
int cloud = myObject["clouds"]["all"];
//OLEDへの距離の表示
display.clearDisplay();
display.setCursor(0,0);
display.setTextSize(1);
display.print("Update: ");
display.println(formattedTime);
display.print("Weather: ");
display.println(myObject["weather"][0]["main"]);
display.print("Temp.: ");
display.printf("%2.1f C\n", tempc-273.15);
display.print("Pressure: ");
display.printf("%4d hPa\n", prs);
display.print("Humidity: ");
display.printf("%2d %%\n", hum);
display.print("Wind Speed: ");
display.printf("%2.2f m/s\n", speed);
display.print("Clouds: ");
display.printf("%3d %%\n", cloud);
display.display();
Serial.println(formattedTime);
Serial.print("JSON object = ");
Serial.println(myObject);
Serial.print("TemperatureC: ");
Serial.println(tempc-273.15);
//Serial.print("Temperature: ");
//Serial.println(myObject["main"]["temp"]);
Serial.print("Pressure: ");
Serial.println(myObject["main"]["pressure"]);
Serial.print("Humidity: ");
Serial.println(myObject["main"]["humidity"]);
Serial.print("Wind Speed: ");
Serial.println(myObject["wind"]["speed"]);
Serial.print("Clouds: ");
Serial.println(myObject["clouds"]["all"]);
}
else {
Serial.println("WiFi Disconnected");
}
lastTime = millis();
}
}
String httpGETRequest(const char* serverName) {
WiFiClient client;
HTTPClient http;
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// Send HTTP POST request
int httpResponseCode = http.GET();
String payload = "{}";
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
payload = http.getString();
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
return payload;
}