Get Weather Data

Start 

This project will allow you to request and display weather data from anywhere you want.

Modules 

Gather the following parts to complete this project.

Parts

All Parts
All Parts
LCD Display
WiFi
Button
Cable
PartQuantity
LCD Display 1
WiFi 1
Button 1
Cable 3

WiFi Module 

Take a cable and unwrap it. Plug one side into the WiFi socket and the other into any Digital socket.

Parts needed
Parts needed
Take a cable
Unwrap it
Plug one side into the WiFi socket
The other into any Digital socket

Upload

Upload the following code. The example below uses the D8 digital pin.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include "WiFiEsp.h"
#include "SoftwareSerial.h"

//Creates serial communication object
SoftwareSerial Serial1(8, 9); // RX, TX

void setup() {
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // Print WiFi MAC address
  printMacAddress();
}

void loop()
{
  // scan for existing networks
  Serial.println();
  Serial.println("Scanning available networks...");
  //function to scan for wifi networks
  listNetworks();
  //Wait 10 seconds before scanning agian
  delay(10000);
}


void printMacAddress()
{
  // get your MAC address
  byte mac[6];
  //This is a unique hardware address for the wifi module
  WiFi.macAddress(mac);

  // print MAC address
  char buf[20];
  //replaces %02X with a MAC address byte
  sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X", mac[5], mac[4], mac[3], mac[2], mac[1], mac[0]);
  Serial.print("MAC address: ");
  Serial.println(buf);
}

void listNetworks()
{
  // scan for nearby networks
  int numSsid = WiFi.scanNetworks();
  //This runs when there isn't a wifi connection
  if (numSsid == -1) {
    Serial.println("Couldn't get a WiFi connection");
    //The Arduino will stay in this loop forever if it can't get a connection
    while (true);
  }

  // print the list of networks seen
  Serial.print("Number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found
  for (int thisNet = 0; thisNet < numSsid; thisNet++) {
    //Print the network number
    Serial.print(thisNet);
    Serial.print(") ");
    //Print network name
    Serial.print(WiFi.SSID(thisNet));
    //Print out the signal strength
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    //Print password type
    Serial.print("\tEncryption: ");
    printEncryptionType(WiFi.encryptionType(thisNet));
  }
}

void printEncryptionType(int thisType) {
  // read the encryption type and print out the name
  switch (thisType) {
    case ENC_TYPE_WEP:
      Serial.print("WEP");
      break;
    case ENC_TYPE_WPA_PSK:
      Serial.print("WPA_PSK");
      break;
    case ENC_TYPE_WPA2_PSK:
      Serial.print("WPA2_PSK");
      break;
    case ENC_TYPE_WPA_WPA2_PSK:
      Serial.print("WPA_WPA2_PSK");
      break;
    case ENC_TYPE_NONE:
      Serial.print("None");
      break;
  }
  Serial.println();
}

Observe

Open up the Serial Monitor and wait for the WiFi module to scan. It will print out a list of all the possible WiFi networks it can connect to. You should see the name of your normal WiFi network.

Modify

Before uploading this next bit of code, swap out ssid with your WiFi network's name and pass with its password.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
/*
 WiFiEsp example: UdpNTPClient
 Get the time from a Network Time Protocol (NTP) time server.
 Demonstrates use of UDP to send and receive data packets
 For more on NTP time servers and the messages needed to communicate with them,
 see http://en.wikipedia.org/wiki/Network_Time_Protocol
*/

#include "WiFiEsp.h"
#include "WiFiEspUdp.h"
#include "SoftwareSerial.h"

//Create channel for communication to wifi module
SoftwareSerial Serial1(8, 9); // RX, TX

//Wifi settings
char ssid[] = "YOURWIFINETOWRK";       // your network SSID (name)
char pass[] = "YOURPASSWORD";      // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

//Location of the time server
char timeServer[] = "time.nist.gov";  // NTP server
unsigned int localPort = 2390;        // local port to listen for UDP packets

//Communication settings
const int NTP_PACKET_SIZE = 48;  // NTP timestamp is in the first 48 bytes of the message
const int UDP_TIMEOUT = 2000;    // timeout in miliseconds to wait for an UDP packet to arrive
byte packetBuffer[NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
WiFiEspUDP Udp;

void setup()
{
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");

  //Open the communication port
  Udp.begin(localPort);
}

void loop()
{
  // send an NTP packet to a time server
  sendNTPpacket(timeServer);

  // wait for a reply for UDP_TIMEOUT miliseconds
  unsigned long startMs = millis();
  while (!Udp.available() && (millis() - startMs) < UDP_TIMEOUT) {

  }
  //Print out the information received
  Serial.println(Udp.parsePacket());
  //If packet is sent from the time server
  if (Udp.parsePacket()) {
    Serial.println("packet received");
    // We've received a packet, read the data from it into the buffer
    Udp.read(packetBuffer, NTP_PACKET_SIZE);

    // the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = ");
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if (((epoch % 3600) / 60) < 10) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ((epoch % 60) < 10) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
void sendNTPpacket(char *ntpSrv)
{
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)

  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  Udp.beginPacket(ntpSrv, 123); //NTP requests are to port 123

  Udp.write(packetBuffer, NTP_PACKET_SIZE);

  Udp.endPacket();
}

Observe Again

Open up the Serial Monitor and check it out. You should connect to your WiFi network then you'll see reports with the time in the UNIX standard. If it doesn't connect make sure your ssid and pass are correct. If you see the time being reported then you're ready for the next step.

Getting the Weather Data 

Take a cable and unwrap it. Plug one side into the LCD socket and the other into any I2C socket. Take another cable and unwrap it. Plug one side into the button socket and the other into any Digital socket.

Take a cable
Take a cable
Unwrap it
Plug one side into the LCD socket
The other into any I2C socket
Take another cable
Unwrap it
Plug one side into the button socket
The other into any Digital socket

Upload

Upload the following code. Replace ssid with your network name from above as well as pass. Replace CITY and STATE with your location. This example uses D4 for the button.

Download file Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#include "WiFiEsp.h"
#include "SoftwareSerial.h"
#include "rgb_lcd.h"
#include "OneButton.h"

//Create objects
rgb_lcd lcd;
SoftwareSerial Serial1(8, 9); // RX, TX
WiFiEspClient client;
OneButton button(4, false);

//Wifi settings
char ssid[] = "YOURNETWORK";       // your network SSID (name)
char pass[] = "YOURPASSWORD";      // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

// Weather Options
// State can be country
// Any spaces must be replcaed with '%20'
// Example: "Buenos Aires" -> "Buenos%20Aries"
#define CITY "Buffalo"
#define STATE "NY"

// Weather Variables
int temp;
int humidity;
float pressure;
String outside;

// Server and URL
char server[] = "query.yahooapis.com";
#define url "/v1/public/yql?q=select%20item.condition.temp%2C%20atmosphere.humidity%2Catmosphere.pressure%2Citem.condition.text%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22" CITY "%2C%20" STATE "%22)&format=json"

//Misc Variables
int lcdPos = 0;
int infoCount = 1;
bool firstUpdate = true;

//LCD color in RGB
const int colorR = 50;
const int colorG = 50;
const int colorB = 25;

//How long to wait before updating weather
const long interval = 300000;

//Time storable variables
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {

  //Intialize LCD
  lcd.begin(16, 2);
  lcd.setRGB(colorR, colorG, colorB);
  lcd.setCursor(0, 0);
  lcd.print("Setting WiFi");

  //Intialize button
  button.attachClick(buttonClick);

  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  // you're connected now, so print out the data
  Serial.println("You're connected to the network");
}

void loop() {
  //Update time and check button
  currentMillis = millis();
  button.tick();

  //Run is first time or enough time has passed
  if (currentMillis - previousMillis >= interval || firstUpdate) {
    Serial.println("Updating");
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Updating Weather...");
    //Try and send the data
    if (client.connect(server, 80)) {
      // Make a HTTP request:
      client.println(String("GET ") + url + String(" HTTP/1.1"));
      client.println("Host: query.yahooapis.com");
      client.println("Connection: close");
      client.println();
    }

    //Wait in this loop until you get a response
    while ( !client.available() ) {
      delay(1);
    }

    //Ask for the four variables
    switch (infoCount) {
      case 1:
        //Ask for Temperature
        if ( client.find("temp\":") ) {
          //Store the value
          temp = client.parseInt();
          //Display it to serial monitor
          Serial.print("Temperature: ");
          Serial.print(temp);
          Serial.println(" F");
          //Stop the connection
          client.flush();
          client.stop();
        }
        //Set to next variable
        infoCount++;
        //exits the switch case
        break;

      case 2:
      //Ask for Humidity
        if ( client.find("humidity\":") ) {
          //Store the value
          humidity = client.parseInt();
          //Display it to serial monitor
          Serial.print("Humidity: ");
          Serial.print(humidity);
          Serial.println(" %");
          //Stop the connection
          client.flush();
          client.stop();
        }
        //Set to next variable
        infoCount++;
        //exits the switch case
        break;

      case 3:
      //Ask for Pressure
        if ( client.find("pressure\":") ) {
          //Store the variable
          pressure = client.parseFloat();
          //Display it to serial monitor
          Serial.print("Pressure: ");
          Serial.print(pressure);
          Serial.println(" kPa");
          //Stop the connection
          client.flush();
          client.stop();
        }
        //Set to next variable
        infoCount++;
        //Set to next variable
        break;

      case 4:
      //Ask for a text description of the weather
        if ( client.find("text\":\"") ) {
          //Store the response
          outside = client.readStringUntil('"');
          //Display it to serial monitor
          Serial.print("Outside is ");
          Serial.print(outside);
          //Update time
          previousMillis = currentMillis;
          //Fake press button to show values
          buttonClick();
          firstUpdate = false;
          //Stop the connection
          client.flush();
          client.stop();
        }
        //Set count back to first one for next update
        infoCount = 1;
        break;
    }
    // if the server's disconnected, stop the client:
    if (!client.connected()) {
      Serial.println();
      Serial.println("disconnecting from server.");
      client.flush();
      client.stop();
    }
  }
}

//What to do when the button is pressed
void buttonClick() {
  //We only have 3 states for the buttons
  if (lcdPos < 2) {
    lcdPos++;
  } else {
    //If the lcdPos is about to go out of bounds
    //Reset it
    lcdPos = 0;
  }
  //Clear all characters from the display
  lcd.clear();
  //Display info based on the lcdPos variable
  switch (lcdPos) {
    case 0:
    //Set cursor to the top left
      lcd.setCursor(0, 0);
      //Print a generic statement
      lcd.print("Showing Weather");
      //Set cursor to bottom left
      lcd.setCursor(0, 1);
      //Display CITY variable
      lcd.print(CITY);
      //exit switch case
      break;

    case 1:
    //Set cursor to the top left
      lcd.setCursor(0, 0);
      lcd.print("Humidity = ");
      //Set cursor after the previous statement
      lcd.setCursor(11, 0);
      //Print humidity variable
      lcd.print(humidity);
      //Set cursor to bottom left
      lcd.setCursor(0, 1);
      lcd.print("Tem = ");
      //Set cursor to bottom left
      lcd.setCursor(6, 1);
      //Print out the temperature variable
      lcd.print(temp);
      //Move cursor to after the variable
      lcd.setCursor(8, 1);
      //Print the unit
      lcd.print("F");
      //exit the switch case
      break;

    case 2:
    //Set cursor to the top left
      lcd.setCursor(0, 0);
      lcd.print("Press = ");
      //Set cursor after the previous statement
      lcd.setCursor(8, 0);
      //Print out the pressure variable
      lcd.print(pressure);
      //Move cursor after variable
      lcd.setCursor(13, 0);
      //Print the unit
      lcd.print("kPa");
      //Set cursor to bottom left
      lcd.setCursor(0, 1);
      //Print out the description
      lcd.print(outside);
      //exit the switch case
      break;
  }
}

Observe

Open up the Serial Monitor to see every step the project is taking before the information gets to the LCD Display. Press the button to cycle through the conditions.

Booting up
Booting up
Getting weather data
Displaying conditions
Displaying conditions
Displaying location

Modify

Change the interval to change the update rate. It is expressed in milliseconds. 1 minute is 60000 milliseconds.