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