ESP32 using Weather API and Blink as Output

Hello,

I am currently working with an ESP32 using a Weather API to pull data as a JSON and I want to check the values like temperature, wind speed, etc. at a certain value there should be an output, in this case i want to blink an LED to test it.

At the moment I can pull the data and print the certain values I want to use but I have no clue how to extract them not as a string to print but to use as a value for an if statement.

Could anyone help me with that and point me in the right direction?

#include < WiFi.h >
#include < HTTPClient.h >
#include < Arduino_JSON.h >

const char* ssid = "xxxxx";
const char* password = "xxxx";

String openWeatherMapApiKey = "c66687d91d685f5ecdda0007dxxxxxxx";

String city = "Berlin";
String countryCode = "BER";

unsigned long lastTime = 0;
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {
    Serial.begin(115200);


    WiFi.begin(ssid, password);
    Serial.println("Connecting");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    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.");
}

void loop() {
    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);

            if (JSON.typeof(myObject) == "undefined") {
                Serial.println("Parsing input failed!");
                return;
            }

            Serial.print("JSON object = ");
            Serial.println(myObject);
            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"]);

        }

        if (myObject["wind"]["speed"] >= 3) {
            delay(1000);
            digitalWrite(ONBOARD_LED, HIGH);
            delay(100);
            digitalWrite(ONBOARD_LED, LOW);
        }
    }

    else {
        Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
}
}

String httpGETRequest(const char* serverName) {
    WiFiClient client;
    HTTPClient http;

    http.begin(client, serverName);

    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;
}

That stuff is from an older version of ArduinoJson. Here is an example that uses V6 of ArduinoJson:

#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>

WiFiMulti WiFiMulti;

#include <ArduinoJson.h>

// set Wi-Fi SSID and password
const char *ssid = "Your WiFi SSID";
const char *password = "Your WiFi Password";

// set location and API key
String Location = "Berlin";
String API_Key = "c66687d91d685f5ecdda0007dxxxxxxx";

void setup()
{
  Serial.begin(115200);
  delay(200);

  WiFiMulti.addAP(ssid, password);

  Serial.print("Connecting.");
}

void loop()
{
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED))
  {
    WiFiClient client;
    HTTPClient http;
    String payload;

    // specify request destination
    Serial.print("[HTTP] begin...\n");
    if (http.begin(client, "http://api.openweathermap.org/data/2.5/weather?q=" + Location + "&APPID=" + API_Key))    // HTTP
    {

      Serial.print("[HTTP] GET...\n");
      // start connection and send HTTP header
      int httpCode = http.GET();

      // httpCode will be negative on error
      if (httpCode > 0) // check the returning code
      {
        // HTTP header has been send and Server response header has been handled
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY)
        {
          payload = http.getString();
          Serial.println(payload);
        }
      }
      else
      {
        Serial.printf("[HTTP] GET... failed, error: %s\n",
                      http.errorToString(httpCode).c_str());
        return;
      }

      /*
         {"coord":{"lon":77.75,"lat":20.9333},
         "weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],
         "base":"stations","main":{"temp":301.45,"feels_like":303.3,"temp_min":301.45,
         "temp_max":301.45,"pressure":1004,"humidity":62,"sea_level":1004,"grnd_level":966},
         "visibility":10000,"wind":{"speed":3.14,"deg":293,"gust":7.39},"clouds":{"all":94},
         "dt":1628958953,"sys":{"country":"IN","sunrise":1628900858,"sunset":1628947200},
         "timezone":19800,"id":1278718,"name":"Amrāvati","cod":200}
      */

      StaticJsonDocument<1024> doc;

      DeserializationError error = deserializeJson(doc, payload);

      if (error)
      {
        Serial.print(F("deserializeJson() failed: "));
        Serial.println(error.f_str());
        return;
      }

      //      float coord_lon = doc["coord"]["lon"]; // 77.75
      //      float coord_lat = doc["coord"]["lat"]; // 20.9333
      //
      //      JsonObject weather_0 = doc["weather"][0];
      //      int weather_0_id = weather_0["id"]; // 804
      //      const char* weather_0_main = weather_0["main"]; // "Clouds"
      //      const char* weather_0_description = weather_0["description"]; // "overcast clouds"
      //      const char* weather_0_icon = weather_0["icon"]; // "04n"
      //
      //      const char* base = doc["base"]; // "stations"
      //
      JsonObject main = doc["main"];
      float main_temp = main["temp"]; // 301.45
      //      float main_feels_like = main["feels_like"]; // 303.3
      //      float main_temp_min = main["temp_min"]; // 301.45
      //      float main_temp_max = main["temp_max"]; // 301.45
      float main_pressure = main["pressure"]; // 1004
      int main_humidity = main["humidity"]; // 62
      //      int main_sea_level = main["sea_level"]; // 1004
      //      int main_grnd_level = main["grnd_level"]; // 966
      //
      //      int visibility = doc["visibility"]; // 10000
      //
      JsonObject wind = doc["wind"];
      float wind_speed = wind["speed"]; // 3.14
      int wind_deg = wind["deg"]; // 293
      //      float wind_gust = wind["gust"]; // 7.39
      //
      //      int clouds_all = doc["clouds"]["all"]; // 94
      //
      //      long dt = doc["dt"]; // 1628958953
      //
      //      JsonObject sys = doc["sys"];
      //      const char* sys_country = sys["country"]; // "IN"
      //      long sys_sunrise = sys["sunrise"]; // 1628900858
      //      long sys_sunset = sys["sunset"]; // 1628947200
      //
      //      int timezone = doc["timezone"]; // 19800
      //      long id = doc["id"]; // 1278718
      //      const char* name = doc["name"]; // "Amrāvati"
      //      int cod = doc["cod"]; // 200


      // print data
      Serial.printf("Temperature = %.2f°C\r\n", main_temp);
      Serial.printf("Humidity = %d %%\r\n", main_humidity);
      Serial.printf("Pressure = %.3f bar\r\n", main_pressure);
      Serial.printf("Wind speed = %.1f m/s\r\n", wind_speed);
      Serial.printf("Wind degree = %d°\r\n\r\n", wind_deg);
    }
    else
    {
      Serial.println("[HTTP] .begin() failed");
    }

    http.end(); //Close connection
  }

  delay(60000); // wait 1 minute
}
// End of code.

If I'm understanding your question correctly, you're able to get the data you need from the API, but it's coming as strings and you want numeric values. In this case, the C function atoi() can help. It takes ASCII (string) and gives you an integer. There is also atof(), for ASCII to float, though I have never used it. c++ - like atoi but to float - Stack Overflow has more information on that.

If you need to do the reverse operation (integer or float converted to string) check out sprintf() and snprintf().

johnwasser,
your example seems to be working, i can also see some things that look familiar but I couldn't use in the other code.
So now I can move on to the next stage.

Thank you!

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.