Can't use webAPI to do a simple LED blink

hiya,

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.

I encountered a problem. I tried to include a blink using an if statement regarding certain values. Also I used millis() instead of the delay.
For now the code is kind of working, but the LED is actually not blinking but changes every loop from HIGH to LOW, also I am not certain that it actually reacts to the value in the if statement.

For more clarity in the end the programm should check every few minutes the weather and if I get certain values I want to drive a DC Motor for a couple of seconds then stop it and then start it again.

So I want it to switch multiple times between on and off during one loop. And then the whole loop (including the pull of data) should start again.

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

WiFiMulti WiFiMulti;

#include <ArduinoJson.h>

int ledPin =  22;      // the number of the LED pin
int ledState = LOW;             // ledState used to set the LED

unsigned long previousMillis = 0;        // will store last time LED was updated
long OnTime = 250;           // milliseconds of on-time
long OffTime = 750;          // milliseconds of off-time
long WaitTime = 10000;

// set Wi-Fi SSID and password
const char *ssid = "xxxxxx";
const char *password = "xxxxxx";

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


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

  pinMode(ledPin, OUTPUT);


  WiFiMulti.addAP(ssid, password);

  Serial.print("Connecting.");
}

void loop()
{
  unsigned long currentMillis = millis();

  if ((currentMillis - previousMillis) > WaitTime) {  // 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);


        if ((ledState == LOW) && (main_temp >= 200) && (currentMillis - previousMillis >= OnTime)) {
          ledState = HIGH;  // Turn it off
          previousMillis = currentMillis;  // Remember the time
          digitalWrite(ledPin, ledState);  // Update the actual LED
        }
        else if ((ledState == HIGH) && (main_temp >= 200) && (currentMillis - previousMillis >= OffTime)) {
          ledState = LOW;  // turn it on
          previousMillis = currentMillis;   // Remember the time
          digitalWrite(ledPin, ledState);    // Update the actual LED
        }
      }
      else
      {
        Serial.println("[HTTP] .begin() failed");
      }

      http.end(); //Close connection
    }
    previousMillis = currentMillis;
  }
  if (currentMillis < previousMillis + WaitTime) {
  }
}

You only execute those statements every WaitTime milliseconds which is 10000 so each time through the loop, currentMillis - previousMillis will always be greater than your on/off time. That code needs to be moved outside your initial if() statement so it runs every time through loop()

Something like this (untested)

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

WiFiMulti WiFiMulti;

#include <ArduinoJson.h>

const int ledPin =  22;      // the number of the LED pin
bool shouldBlink;

unsigned long previousMillis = 0;        // will store last time LED was updated
const unsigned long WaitTime = 10000;

// set Wi-Fi SSID and password
const char *ssid = "xxxxxx";
const char *password = "xxxxxx";

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


void setup()
{
  Serial.begin(115200);
  delay(200);
  pinMode(ledPin, OUTPUT);

  WiFiMulti.addAP(ssid, password);
  Serial.print("Connecting.");
}


void loop()
{
  unsigned long currentMillis = millis();

  if ((currentMillis - previousMillis) >= WaitTime) {  // wait for WiFi connection
    fetchInfo();
    previousMillis = currentMillis;
  }

  if ( shouldBlink ) {
    blinkLED();
  }
  else {
    digitalWrite(ledPin, HIGH);    // off
  }
}

void blinkLED() {
  const unsigned long OnTime = 250;           // milliseconds of on-time
  const unsigned long OffTime = 750;          // milliseconds of off-time

  static int ledState = HIGH;
  static unsigned long duration = OnTime;
  static unsigned long lastTime;

  if ( millis() - lastTime < duration ) {
    return;
  }
  lastTime = millis();
  if ( ledState == LOW ) {
    ledState = HIGH;  // Turn it off
    duration = OffTime;
  }
  else {
    ledState = LOW;  // turn it on
    duration = OnTime;
  }
  digitalWrite(ledPin, ledState);    // Update the actual LED
}


void fetchInfo() {
  if ((WiFiMulti.run() != WL_CONNECTED)) {
    Serial.println(F("Not Connected"));
    return;
  }
  
  WiFiClient client;
  HTTPClient http;
  String payload;

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

  Serial.print("[HTTP] GET...\n");
  int httpCode = http.GET();

  // httpCode will be negative on error
  if (httpCode < 0)  {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    return;
  }
  Serial.printf("[HTTP] GET... code: %d\n", httpCode);
  if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
    payload = http.getString();
    Serial.println(payload);
  }

  /*
     {"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;
  }

  JsonObject main = doc["main"];
  float main_temp = main["temp"]; // 301.45
  float main_pressure = main["pressure"]; // 1004
  int main_humidity = main["humidity"]; // 62
  JsonObject wind = doc["wind"];
  float wind_speed = wind["speed"]; // 3.14
  int wind_deg = wind["deg"]; // 293

  // 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);

  if ( main_temp >= 200.0 ) {
    shouldBlink = true;
  }
  else {
    shouldBlink = false;
  }

  http.end(); //Close connection
}

after my first tests, it seems to work without problems. thank you so much!

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