(IOT Project) Get Weather Data Using ESP8266 and Openweather API

by tinkerbuildlearn in Circuits > Microcontrollers

2448 Views, 0 Favorites, 0 Comments

(IOT Project) Get Weather Data Using ESP8266 and Openweather API

+.png

In this instructable we are going to build a simple IOT project in which fetch the weather data of our city from openweather.com/api and display it using Processing software.

Supplies

  1. Arduino
  2. ESP8266 or any other esp module
  3. Arduino IDE
  4. Processing software
  5. Breadboard
  6. Jumperwires Male to Male and Male to Female

Obtain API Key and URL From Openweather.org

OpenWeather-apisign.png
OpenWeather-apikeys.png
OpenWeather-api.png
OpenWeather-apiAPI.png
OpenWeather-api2.png
OpenWeather-api3.png

  1. Create account in https://openweathermap.org (Image 1)
  2. After you login go to API keys and you will get the API key as shown in image.(Image 2)
  3. Copy the API key and save it in a notepad file.(Image 3)
  4. Go to the API option (Image 4)
  5. Go to API doc option as shown in image (Image 5)
  6. Copy the url from the and shown and save it in a notepad file (Image 6)

Connection Diagram

ckt2.png

Arduino Code

Before copying this code into Arduino make sure you have downloaded ESP8266 board into arduino ide using Boards manager.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <Arduino_JSON.h>

const char* ssid = "Your SSID";
const char* password = "Your SSID PASSWORD";// Your Domain name with URL path or IP address with path
String openWeatherMapApiKey = "Paste your API key here";

// Replace with your country code and city
String city = "Mumbai";
String countryCode = "IN";
String data[16];
// 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;

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() {
  // 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 + "&units=metric";
      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;
      }
//      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"]);
 int temp = myObject["main"]["temp"];
  long pres = myObject["main"]["pressure"];
    int humid = myObject["main"]["humidity"];
     int wind = myObject["wind"]["speed"];
      
     
     
      String country = JSON.stringify(myObject["sys"]["country"]);
        String city1 = JSON.stringify(myObject["name"]); 
         String weather = JSON.stringify(myObject["weather"][0]["description"]);
          String icon = JSON.stringify(myObject["weather"][0]["icon"]);
          
          
     
      data[0]= String(temp);
      data[1]= "/";
      data[2]= String(pres);
      data[3]= "/";
      data[4]= String(humid);
      data[5]= "/";
      data[6]= String(wind);
      data[7]= "/";
      data[8]= country;
      data[9]= "/";
      data[10]= city1;
      data[11]= "/";
      data[12]= weather;
      data[13]= "/";
      data[14]= icon;
      data[15]= "\n";
      
  for(int i=0;i<=15;i++){
      Serial.print(data[i]);
  }
    }
    else {
      //Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

String httpGETRequest(const char* serverName) {
  HTTPClient http;
    
  // Your IP address with path or Domain name with URL path 
  http.begin(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;
} 

Processing Code

01d.png
01n.png
02d.png
02n.png
03d.png
03n.png
04d.png
04n.png
09d.png
09n.png
10d.png
10n.png
11d.png
11n.png
13d.png
13n.png
50d.png
50n.png

Before running this code download the given icon images which will be used to show weather. And keep the images and code in the same folder.

import processing.serial.*; 
Serial myPort;
PImage img;
PImage img2;
PImage img3;
PImage img4;
PImage img5;
PImage img6;
PImage img7;  
PImage img8;
PImage img9;
PImage img10;
PImage img11;
PImage img12;
PImage img13;
PImage img14;
PImage img15;
PImage img16;
PImage img17;
PImage img18;

int temp;
int pres;
int humid;
int wind;
String city = " ";
String country = " "; 
String weather =" ";
String icon = " "; 
void setup(){
 size(500,500);
 myPort = new Serial(this,"COM3",115200);
 img = loadImage("01d.png");
 img2 = loadImage("01n.png");
 img3 = loadImage("02d.png");
 img4 = loadImage("02n.png");
 img5 = loadImage("03d.png");
 img6 = loadImage("03n.png");
 img7 = loadImage("04d.png");
 img8 = loadImage("04n.png");
 img9 = loadImage("09d.png");
 img10 = loadImage("09n.png");
 img11 = loadImage("10d.png");
 img12 = loadImage("10n.png");
 img13 = loadImage("11d.png");
 img14 = loadImage("11n.png");
 img15 = loadImage("13d.png");
 img16 = loadImage("13n.png");
 img17 = loadImage("50d.png");
 img18 = loadImage("50n.png"); 
}

void draw(){
     background(72,209,204);
     textSize(22); 
     fill(54, 69, 79);
     text("Temperature: ",25,100);
     text(temp +"°C",200,100);
     text("Pressure:",25,150);
     text(pres + " hpa",200,150);
     text("Humidity: ",25,200);
     text(humid+" %",200,200);
     text("Wind: ",25,250); 
     text(wind+" m/s",200,250);
     text("Country/City: ",25,300); 
     text(country +"-"+ city,200,300);
     text("Weather: ",25,350); 
     text(weather,200,350);
     
     if(icon.contains("01d")){
         image(img, 380, 15);
         
       }
      else if(icon.contains("01n")){
         image(img2,  380, 15);
         
       }
       else if(icon.contains("02d")){
         image(img3,  380, 15);
         
       }
       else if(icon.contains("02n")){
         image(img4,  380, 15);
         
       }
       else if(icon.contains("03d")){
         image(img5, 380, 15);
         
       }
       else if(icon.contains("03n")){
         image(img6, 380, 15);
         
       }
       else if(icon.contains("04d")){
         image(img7, 380, 15);
         
       }
       else if(icon.contains("04n")){
         image(img8, 380, 15);
         
       }
       else if(icon.contains("09d")){
         image(img9,  380, 15);
         
       }
       else if(icon.contains("09n")){
         image(img10, 380, 15);
         
       }
       else if(icon.contains("10d")){
         image(img11, 380, 15);
         
       }
       else if(icon.contains("10n")){
         image(img12,  380, 15);
         
       }
       else if(icon.contains("11d")){
         image(img13,  380, 15);
         
       }
       else if(icon.contains("11n")){
         image(img14,  380, 15);
         
       }
       else if(icon == "13d"){
         image(img15,  380, 15);
         
       }
       else if(icon.contains("13n")){
         image(img16,  380, 15);
         
       }
       else if(icon.contains("50d")){
         image(img17, 380, 15);
         
       }
       else if(icon.contains( "50n")){
         image(img18, 380, 15);
         
       }
     
}

 
void serialEvent(Serial myPort){
  if (myPort.available() > 0){
     String data = myPort.readStringUntil('\n');
  if(data != null){  
    data = trim(data);
    String items[] = split(data, '/');
    if (items.length > 1) {
      temp = int(items[0]);
       pres = int(items[1]);
       humid = int(items[2]);
       wind = int(items[3]);
       city = items[4].replace("\"","");
       country = items[5].replace("\"","");
       weather = items[6].replace("\"","");
       icon =  items[7].replace("\"","");    
     }   
}
}
}<strong>
    <br></strong>

Project Output

op.png