· 6 years ago · Oct 16, 2019, 08:44 AM
1#include "arduino_secrets.h"
2#include <ArduinoJson.h>
3#include <SPI.h>
4#include <WiFi101.h>
5
6
7char ssid[] = SECRET_SSID; // your network SSID (name)
8char pass[] = SECRET_PSW;// your network PASSWORD ()
9
10//open weather map api key
11String apiKey= SECRET_APIKEY;
12
13//the city you want the weather for
14String location= "Lahti,FI";
15
16int status = WL_IDLE_STATUS;
17char server[] = "api.openweathermap.org";
18
19WiFiClient client;
20
21
22void setup() {
23 // Initialize serial and wait for port to open:
24 Serial.begin(9600);
25 while (!Serial) {
26 ; // wait for serial port to connect. Needed for native USB port only
27 }
28
29 // check for the presence of the shield:
30 if (WiFi.status() == WL_NO_SHIELD) {
31 Serial.println("WiFi shield not present");
32 // don't continue:
33 while (true);
34 }
35
36 // attempt to connect to WiFi network:
37 while ( status != WL_CONNECTED) {
38 Serial.print("Attempting to connect to WPA SSID: ");
39 Serial.println(ssid);
40 // Connect to WPA/WPA2 network:
41 status = WiFi.begin(ssid, pass);
42
43 // wait 5 seconds for connection:
44 delay(5000);
45 }
46 Serial.println("Connected to wifi");
47}
48
49void loop() {
50 getWeather();
51 delay(10000);
52}
53
54
55void getWeather() {
56
57 Serial.println("\nStarting connection to server...");
58 // if you get a connection, report back via serial:
59 if (client.connect(server, 80)) {
60 Serial.println("connected to server");
61 // Make a HTTP request:
62 client.print("GET /data/2.5/forecast?");
63 client.print("q="+location);
64 client.print("&appid="+apiKey);
65 client.print("&cnt=3");
66 client.println("&units=metric");
67 client.println("Host: api.openweathermap.org");
68 client.println("Connection: close");
69 client.println();
70 } else {
71 Serial.println("unable to connect");
72 }
73
74 delay(1000);
75 String line = "";
76
77 while (client.connected()) {
78 line = client.readStringUntil('\n');
79
80 //Serial.println(line);
81 Serial.println("parsingValues");
82
83 //create a json buffer where to store the json data
84 StaticJsonBuffer<5000> jsonBuffer;
85
86 JsonObject& root = jsonBuffer.parseObject(line);
87 if (!root.success()) {
88 Serial.println("parseObject() failed");
89 return;
90 }
91
92 //get the data from the json tree
93 String nextWeatherTime0 = root["list"][0]["dt_txt"];
94 String nextWeather0 = root["list"][0]["weather"][0]["main"];
95
96 String nextWeatherTime1 = root["list"][1]["dt_txt"];
97 String nextWeather1 = root["list"][1]["weather"][0]["main"];
98
99 String nextWeatherTime2 = root["list"][2]["dt_txt"];
100 String nextWeather2 = root["list"][2]["weather"][0]["main"];
101
102 // Print values.
103 Serial.println(nextWeatherTime0);
104 Serial.println(nextWeather0);
105 Serial.println(nextWeatherTime1);
106 Serial.println(nextWeather1);
107 Serial.println(nextWeatherTime2);
108 Serial.println(nextWeather2);
109
110 }
111}