I'm trying to get my head around using openweathermap.org info.
I have an APIkey , as well as my city info, working on a weather station.
I'm trying no to only retrieve the temperature for the location.
With the following sketch I get "Error code: -1"
I added to the sketch a few testing points and it seem that error comes after executing the line "if (httpResponseCode > 0) {"
Here is the sketch:
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
// Wi-Fi Credentials
const char* ssid = "Pajura1";
const char* password = "sugipula2015!";
// OpenWeatherMap API Details
// Example URL: api.openweathermap.org/data/2.5/weather?q=Brossard,CA&appid=YOUR_API_KEY&units=metric
String apiKey = "7fedc1d7e597836c7793ca30d42826e1";
String city = "5909629"; // Or your specific city
String countryCode = "CA";
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WIFI connected");
HTTPClient http;
// Construct the API request URL
String serverPath = "http://openweathermap.org" + city + "," + countryCode + "&appid=" + apiKey + "&units=metric";
http.begin(serverPath.c_str());
int httpResponseCode = http.GET();
Serial.println("1");
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println("2");
// Parse the JSON response
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
Serial.println("3");
float temp = doc["main"]["temp"];
Serial.print("Current outdoor temperature in ");
Serial.print(city);
Serial.print(": ");
Serial.print(temp);
Serial.println(" °C");
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
delay(60000); // Wait 1 minute before requesting again
It's two different things, Name and ID and they are both used in different places. I will pluck out just those lines of code, the weather station code is many files and tons of code. I did NOT write it.
// Update the internet based information and update screen
void updateData() {
time_t now = time(nullptr);
gfx.fillBuffer(MINI_BLACK);
gfx.setFont(ArialRoundedMTBold_14);
drawProgress(50, "Updating conditions...");
OpenWeatherMapCurrent *currentWeatherClient = new OpenWeatherMapCurrent();
currentWeatherClient->setMetric(IS_METRIC);
currentWeatherClient->setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
currentWeatherClient->updateCurrentById(¤tWeather, OPEN_WEATHER_MAP_API_KEY, OPEN_WEATHER_MAP_LOCATION_ID);
delete currentWeatherClient;
currentWeatherClient = nullptr;
drawProgress(70, "Updating forecasts...");
OpenWeatherMapForecast *forecastClient = new OpenWeatherMapForecast();
forecastClient->setMetric(IS_METRIC);
forecastClient->setLanguage(OPEN_WEATHER_MAP_LANGUAGE);
uint8_t allowedHours[] = {12, 0};
forecastClient->setAllowedHours(allowedHours, sizeof(allowedHours));
forecastClient->updateForecastsById(forecasts, OPEN_WEATHER_MAP_API_KEY, OPEN_WEATHER_MAP_LOCATION_ID, MAX_FORECASTS);
delete forecastClient;
forecastClient = nullptr;
void loadPropertiesFromSpiffs() {
if (SPIFFS.begin()) {
const char *msg = "Using '%s' from SPIFFS\n";
Serial.println("Attempting to read application.properties file from SPIFFS.");
File f = SPIFFS.open("/application.properties", "r");
if (f) {
Serial.println("File exists. Reading and assigning properties.");
while (f.available()) {
String key = f.readStringUntil('=');
String value = f.readStringUntil('\n');
if (key == "ssid") {
WIFI_SSID = value.c_str();
Serial.printf(msg, "ssid");
} else if (key == "password") {
WIFI_PASS = value.c_str();
Serial.printf(msg, "password");
} else if (key == "timezone") {
TIMEZONE = getTzInfo(value.c_str());
Serial.printf(msg, "timezone");
} else if (key == "owmApiKey") {
OPEN_WEATHER_MAP_API_KEY = value.c_str();
Serial.printf(msg, "owmApiKey");
} else if (key == "owmLocationId") {
OPEN_WEATHER_MAP_LOCATION_ID = value.c_str();
Serial.printf(msg, "owmLocationId");
} else if (key == "locationName") {
DISPLAYED_LOCATION_NAME = value.c_str();
Serial.printf(msg, "locationName");
} else if (key == "isMetric") {
IS_METRIC = value == "true" ? true : false;
This worked for me with my WiFi credentials on an ESP32-C3. Surprisingly with plain http instead of https.
I changed the format of the query to use latitude and longitude to match the API example.
It spits out warnings about deprecated JSON usage.
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h> // ver 7.x
// Wi-Fi Credentials
const char* ssid = "Pajura1";
const char* password = "sugipula2015!";
// OpenWeatherMap API Details
// Example URL: api.openweathermap.org/data/2.5/weather?q=Brossard,CA&appid=YOUR_API_KEY&units=metric
String apiKey = "7fedc1d7e597836c7793ca30d42826e1";
String lat = "45.45"; // Brossard, CA
String lon = "-73.47"; // Brossard, CA
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected!");
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WIFI connected");
HTTPClient http;
// Construct the API request URL
String serverPath = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + apiKey + "&units=metric";
Serial.println(serverPath);
http.begin(serverPath.c_str());
int httpResponseCode = http.GET();
Serial.println("1");
if (httpResponseCode > 0) {
String payload = http.getString();
Serial.println("2");
// Parse the JSON response
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
Serial.println("3");
float temp = doc["main"]["temp"];
String city = doc["name"];
Serial.print("Current outdoor temperature in ");
Serial.print(city);
Serial.print(": ");
Serial.print(temp);
Serial.println(" °C");
} else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
}
delay(60000); // Wait 1 minute before requesting again
}
and gives this on the serial console:
11:36:53.289 -> WIFI connected
11:36:53.289 -> http://api.openweathermap.org/data/2.5/weather?lat=45.45&lon=-73.47&appid=7fedc1d7e597836c7793ca30d42826e1&units=metric
11:36:53.289 -> 1
11:36:53.289 -> 2
11:36:53.289 -> 3
11:36:53.289 -> Current outdoor temperature in Brossard: 12.42 °C