Getting weather data




With this tutorial, you will learn how to get the weather data from a web service to your Arduino.

Things used in this project

Hardware components

Arduino MKR1000
Arduino MKR1000
× 1

Story

Get the code here

#include <SPI.h> 
#include <WiFi101.h> 
char ssid[] = SECRET_SSID; //  your network SSID (name) 
char pass[] = SECRET_PSW;//  your network PASSWORD () 
//open weather map api key 
String apiKey= SECRET_APIKEY; 
//the city you want the weather for 
String location= "torino,IT"; 
int status = WL_IDLE_STATUS; 
char server[] = "api.openweathermap.org";     
WiFiClient client; 
void setup() { 
//Initialize serial and wait for port to open: 
Serial.begin(9600); 
// attempt to connect to Wifi network: 
while (status != WL_CONNECTED) { 
Serial.print("Attempting to connect to SSID: "); 
Serial.println(ssid); 
status = WiFi.begin(ssid); 
//use the line below if your network is protected by wpa password  
//status = WiFi.begin(ssid, pass); 
// wait 10 seconds for connection: 
delay(1000); 
} 
Serial.println("Connected to wifi"); 
} 
void loop() { 
getWeather(); 
delay(10000); 
} 
void getWeather() { 
Serial.println("\nStarting connection to server..."); 
// if you get a connection, report back via serial: 
if (client.connect(server, 80)) { 
Serial.println("connected to server"); 
// Make a HTTP request: 
client.print("GET /data/2.5/forecast?"); 
client.print("q="+location); 
client.print("&appid="+apiKey); 
client.print("&cnt=3"); 
client.println("&units=metric"); 
client.println("Host: api.openweathermap.org"); 
client.println("Connection: close"); 
client.println(); 
} else { 
Serial.println("unable to connect"); 
} 
delay(1000); 
String line = ""; 
while (client.connected()) { 
line = client.readStringUntil('\n'); 
Serial.println(line); 
} 
} 

If everything goes well you should be able to open the serial port and see the json data printed in the serial monitor.

Notice, inside the sketch, that most of the code needed to do the HTTP get request is inside the getWeather function. it should look very similar to the url we were using to get the data in the browser.

READ  Scratching with Arduino

Parse the Json data

Now we just need to get only the information that we need from the sketch.

To parse the data we are going to use the Arduino Json library, therefore, if you don’t have it already just go ahead and download it from the Arduino library manager.

Schematics

Code

A very savvy irrigation system

 




This Post / Project can also be found using search terms:

  • topichl4
  • formerbrz
  • graincir
  • how to get weather data from server using arduino

Leave a Comment

*
= 5 + 5

(Spamcheck Enabled)

Read previous post:
Project Gesture Controlled Mouse (Air Mouse) Using Arduino & Accelerometer
Project: Gesture Controlled Mouse (Air Mouse) Using Arduino & Accelerometer

AIR Mouse is also called gesture-controlled mouse and it works based on hand gesture. In this project an accelerometer is...

Close
Scroll to top