Example Code for Arduino-Get the weather with WIFI

This example is used to let you learn how to get weather information and let you experience the information obtained in HTTP which extract data through Json and print it.

Hardware Preparation

Software Preparation

Step

1.You need to install the Arduino_JSON library. Enter Arduino_JSON in Arduino IDE Tools -> Manage Libraries and install the library
Step
2.Register an OpenWeather account to get the weather information we want. Open your browser and go to https://openweathermap.org/appid/ press the sign up button and create a free account.
Step
Click My API Keys to enter the interface for obtaining API
Step
Copy the key here (this key is your only key to get weather information from OpenWeather)
Step
You can fill the Key into the following URL and fill in the city name and its country to get the city weather information: http://api.openweathermap.org/data/2.5/weather?q=yourCityName,yourCountryCode&APPID=yourAPIkey
The following is an example to replace the city (such as Chengdu) of the data you want in yourCityName, yourCountryCode and the country code of the city (such as CN), fill in yourAPIkey which is the API key obtained earlier, the following is the URL of Chengdu, China with the API added:
http://api.openweathermap.org/data/2.5/weather?q=ChengDu,CN&APPID=4de305d0a52ddaceaecba50a757e9968
Copying your URL into your browser will return a set of information corresponding to your local weather. On the day this tutorial was written, we had the following information about the weather in Chengdu, China.
Step

Sample Code

/*
This example learns how to get weather information
*/

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

//Modify WIFI name and password
const char* ssid = "******";//WIFI name
const char* password = "******";//WIFI password

//Fill in the API Key you got
String openWeatherMapApiKey = "4de305d0a52ddaceaecba50a757e9968";
//Example:
//String openWeatherMapApiKey = "4de305d0a52ddaceaecba50a757e9968";

// Fill in your city name and country abbreviation
String city = "ChengDu";
String countryCode = "CN";

//Example:
//String city = "ChengDu";
//String countryCode = "CN";

//Set the interval for obtaining information, the following is used for testing, so it is set to 10 seconds
//You should limit the minimum interval of access time according to the upper limit of the number of times to access the data within the specified time period of the website you need to obtain the data.
unsigned long lastTime = 0;
//Set to get weather data every 10 minutes
//unsigned long timerDelay = 600000;
//Set to get weather data every 10 seconds
unsigned long timerDelay = 10000;

String jsonBuffer;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");

  //Determine if WIFI is connected
  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() {
  //Send HTTP get request
  if ((millis() - lastTime) > timerDelay) {
    //Check if WIFI is connected
    if(WiFi.status()== WL_CONNECTED){
      String serverPath = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "," + countryCode + "&APPID=" + openWeatherMapApiKey;

      //Put the combined URL into the httpGETRequest function to get the text through HTTP get request.
      jsonBuffer = httpGETRequest(serverPath.c_str());
      Serial.println(jsonBuffer);

      //Store the parsed Json object value in the Jsonu buffer
      JSONVar myObject = JSON.parse(jsonBuffer);

      //Determine if the parsing was successful
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }

      Serial.print("JSON object = ");
      Serial.println(myObject);
      Serial.print("Temperature: ");
      //The obtained temperature is actually Kelvin.
      //Kelvin = Celsius + 273.15
      double c = myObject["main"]["temp"];
      c = c-273.15;
      Serial.println(c);
      Serial.print("Pressure: ");
      //myObject["main"]["pressure"], the front is the content of the quotation marks before {}, and the latter is the data after that quotation mark is read
      Serial.println(myObject["main"]["pressure"]);
      Serial.print("Humidity: ");
      Serial.println(myObject["main"]["humidity"]);
      Serial.print("Wind Speed: ");
      Serial.println(myObject["wind"]["speed"]);
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

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

  //Connect URL
  http.begin(client, serverName);

  //Send HTTP site request
  int httpResponseCode = http.GET();

  //This array is used to store the obtained data
  String payload = "{}";

  //Put the obtained data into the array
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }

  //Release resources
  http.end();

  //Return the obtained data for Json processing
  return payload;
}

Result

Result

Member function

  • httpGETRequest(serverPath.c_str());

    Description: Parse the obtained object
  • JSON.typeof(myObject)

    Description: Determine whether the object is in a parsed format

Was this article helpful?

TOP