· 6 years ago · Mar 24, 2020, 10:19 PM
1#include <ArduinoJson.h>
2#include <SPI.h>
3#include <WiFiNINA.h>
4#include "arduino_secrets.h"
5
6char ssid[] = SECRET_SSID; // your network SSID (name)
7char pass[] = SECRET_PSW;// your network PASSWORD ()
8
9//open weather map api key
10String apiKey = SECRET_APIKEY;
11
12//the city you want the weather for
13String location = "philadelphia,US";
14
15int status = WL_IDLE_STATUS;
16char server_name[] = "api.openweathermap.org";
17
18WiFiClient client;
19
20
21void setup() {
22 //Initialize serial and wait for port to open:
23 Serial.begin(9600);
24
25 // attempt to connect to Wifi network:
26 while (status != WL_CONNECTED) {
27 Serial.print("Attempting to connect to SSID: ");
28 Serial.println(ssid);
29
30 //use the line below if your network is protected by wpa password
31 status = WiFi.begin(ssid, pass);
32
33 // wait 10 seconds for connection:
34 delay(10000);
35 Serial.println(status);
36 }
37 Serial.println("Connected to wifi");
38}
39
40void loop() {
41 getWeather();
42 delay(10000);
43}
44
45
46void getWeather() {
47
48 Serial.println("\nStarting connection to server...");
49 // if you get a connection, report back via serial:
50 if (client.connect(server_name, 80)) {
51 Serial.println("connected to server");
52 // Make a HTTP request:
53 client.print("GET /data/2.5/forecast?");
54 client.print("q=" + location);
55 client.print("&appid=" + apiKey);
56 client.print("&cnt=3");
57 client.println("&units=imperial");
58 client.println("Host: api.openweathermap.org");
59 client.println("Connection: close");
60 client.println();
61 } else {
62 Serial.println("unable to connect");
63 }
64
65 delay(1000);
66 String line = "";
67
68 while (client.connected()) {
69 line = client.readStringUntil('\n');
70
71 //Serial.println(line);
72 Serial.print("parsingValues: ");
73 Serial.println(line);
74
75 //create a json buffer where to store the json data
76 DynamicJsonDocument doc(5000);
77 DeserializationError error = deserializeJson(doc, line);
78 if (error){
79 return;
80 }
81
82 //get the data from the json tree
83 String nextWeatherTime0 = doc["list"][0]["dt_txt"];
84 String nextWeather0 = doc["list"][0]["weather"][0]["main"];
85
86 String nextWeatherTime1 = doc["list"][1]["dt_txt"];
87 String nextWeather1 = doc["list"][1]["weather"][0]["main"];
88
89 String nextWeatherTime2 = doc["list"][2]["dt_txt"];
90 String nextWeather2 = doc["list"][2]["weather"][0]["main"];
91
92 String cityLat= doc["city"]["coord"]["lat"];
93
94 // Print values.
95 Serial.println(nextWeatherTime0);
96 Serial.println(nextWeather0);
97 Serial.println(nextWeatherTime1);
98 Serial.println(nextWeather1);
99 Serial.println(nextWeatherTime2);
100 Serial.println(nextWeather2);
101 Serial.println(cityLat);
102
103 }
104}