Displays the current weather, date, and time

Dependencies:   mbed MbedJSONValue mbed-rtos 4DGL-uLCD-SE ESP8266NodeMCUInterface

Welcome to the Smart Weather Clock, which uses WiFi and Bluetooth to give the user a clear date, time, and weather for the day.

This wiki serves to document

  • What components you'll need
  • How these components will be connected
  • How the code gets all the information it needs

Components

LCD Screen

Components / 4D Systems 128 by 128 Smart Color LCD uLCD-144-G2
128 by 128 Color Smart LCD with serial interface and SD card slot

The LCD screen is a 128x128 pixel full color LCD by 4D Systems. A wonderful introduction can be found here.

In the simplest case, we'll only use one screen, but we can (and perhaps should) augment the design to include two.

Import library4DGL-uLCD-SE

Fork of 4DGL lib for uLCD-144-G2. Different command values needed. See https://mbed.org/users/4180_1/notebook/ulcd-144-g2-128-by-128-color-lcd/ for instructions and demo code.

You can buy it from sparkfun.

5V Adapter

The adapter allows us to feed much more power to the MBED and, critically, decouples us from a computer. It's important to remember that on the barrel jack adapter (i.e., the part that goes in the breadboard), the pin closest to the jack is 5V, and the back pin is Ground.

You can get the adapter here, and the barrel jack adapter here

Bluetooth UART Module

This module allows us to interface with the mbed via bluetooth and the ever-helpful AdaFruit Bluetooth App. A great introduction can be found here.

We'll use it to allow the user to set some defaults and API keys. This is stored in persistent flash storage on the LPC 1768 (See the Local File System, but you'll need an SD card if you're using a different MBED device.

You can get the Bluetooth module here.

WiFi Module

The WiFi module is also from AdaFruit, like the Bluetooth module. This allows us to interface with different WiFi networks for internet connectivity. A nice introduction is here.

You can get the WiFi module here.

WiFi Interface!

The current WiFi interface (found here) has some major problems - we're using an augmented version in our code!

Connections

5V Input for MBED

Before you connect the MBED to 5V from the wall, Make sure you have connected it correctly! If you don't, you could brick the MBED.

Thankfully, this is easy to test - when you think you have hooked up the 5V Jack correctly, try lighting a single LED (with a 10K resistor in series). If it lights up - you're good!

Alternatively, you could just plug in the MBED via USB, and just not have the MBED run on the +5V. You'll still need the Wall Adapter, however.

WiFi Module

The WiFi Module has two Grounds - you must connect both!

MBED5V Barrel Jack
Vin+5V (back pin)
GndGnd (pin closest to jack)
MBEDuLCD Cable
5V5V
GndGnd
P09TX
P10RX
P11Reset
MBEDBluetooth UART
5VVin
GndGnd
GndCTS
P27TXO
P28RXI
MBEDWiFi Module
5VV+
GndGnd
GndGnd
P13RX
P14TX
P15Reset

Code

The code works in a fairly logical order:

  1. Connect to the given WiFi, and check that we have all of our API keys
  2. Get the current location via the IP API
  3. Get the current time via the TimeZoneDB
  4. Get the current weather via the OpenWeatherMap API
  5. Continually update the weather, once per minute

Some caveats:

  • Memory seems to be an issue. If I had to guess, it would be the MbedJSONValue JSON parser - instantiating a third one seems to always lead to an MBED OS Fault or an MBED Memory Allocation fault. More insight is needed here.
  • The off-the-shelf ESP8226 Interface doesn't handle receiving correctly - I had to augment the library with recv and recv2. It works in most simple practical use cases.
Revision:
8:d323c6406b47
Parent:
6:ec7829f7cd38
Child:
9:299eb69af04e
--- a/main.cpp	Mon Apr 01 16:56:49 2019 +0000
+++ b/main.cpp	Mon Apr 01 17:00:17 2019 +0000
@@ -42,29 +42,30 @@
 char time_api_key[256];
 char weather_api_key[256];
 
-void time_updater() {
+void time_updater()
+{
     // We're not an interrupt, so take as much time as we need. Infinite loop
     // but wait 1 second between each loop
     struct tm* ltm;
     time_t now;
-    
+
     now = time(NULL);
     ltm = localtime(&now);
-    
+
     // Buffer for time string. Max length is 23:59 + \0
     int max_time_len = 8;
     char ftime[max_time_len];
     ftime[0] = ' ';
     ftime[1] = ' ';
     int min = -1;
-    
+
     while (true) {
         // if the minute has changed, update.
         now = time(NULL);
         ltm = localtime(&now);
         if(ltm->tm_min != min) {
             // Get the new time
-            strftime(ftime + 2, max_time_len, "%H:%M", ltm); 
+            strftime(ftime + 2, max_time_len, "%H:%M", ltm);
             // Update time! Lock the lcd mutex
             lcd_lock.lock();
             uLCD.text_width(2);
@@ -76,10 +77,11 @@
         }
         // Wait 1 second
         Thread::wait(1.0f);
-    }   
+    }
 }
 
-void dev_recv() {
+void dev_recv()
+{
     // Continually check if we have stuff...
     char buf[1024];
     int ind = 0;
@@ -105,15 +107,17 @@
     }
 }
 
-int kelvin2farenheit(int temp) {
-     return (int)((((temp - 273.15f) * 9.0f) / 5.0f) + 32.0f);
+int kelvin2farenheit(int temp)
+{
+    return (int)((((temp - 273.15f) * 9.0f) / 5.0f) + 32.0f);
 }
 
-void clock_init() {
+void clock_init()
+{
     // Set up bluetooth
     dev.baud(9600);
     pc.baud(9600);
-    
+
     // Tell user we're initializing...
     lcd_lock.lock();
     uLCD.cls();
@@ -122,15 +126,15 @@
     uLCD.text_string("PLEASE", 0, 2, FONT_7X8, WHITE);
     uLCD.text_string("WAIT", 0, 5, FONT_7X8, WHITE);
     lcd_lock.unlock();
-    
+
     // Need to get wifi settings. If we don't have local file, then ask!
     FILE* fid = fopen("/local/settings.txt", "r");
-    
+
     if (fid != NULL) {
         // Read WiFi Settings
         char settings_buf[1024];
         // Guaranteed to be 5 lines
-        // 
+        //
         fgets(settings_buf, 1024, fid);
         // find \n
         int settings_ind = 0;
@@ -176,16 +180,16 @@
         uLCD.text_string("SEE", 0, 2, FONT_7X8, RED);
         uLCD.text_string("DEVICE", 0, 5, FONT_7X8, RED);
         lcd_lock.unlock();
-        
+
         // Ask!
         dev.printf("Please provide the name of a WiFi Network\n");
-        
+
         // Wait for them to respond
         while (!dev.readable()) {
             wait(0.001);
         }
         int ind = 0;
-        
+
         // Read response
         while (ind < 255) {
             char tmp = dev.getc();
@@ -196,13 +200,13 @@
             wait(0.01);
         }
         ssid[ind] = '\0';
-        
+
         // flush device
         while (dev.readable()) {
             dev.getc();
             wait(0.01);
         }
-        
+
         // Get the password
         dev.printf("Please provide the password\n");
         while (!dev.readable()) {
@@ -218,7 +222,7 @@
             wait(0.01);
         }
         pass[ind] = '\0';
-        
+
         // Get the API key
         dev.printf("Please provide the IP Stack API key\n");
         while (!dev.readable()) {
@@ -235,7 +239,7 @@
         }
 
         ip_api_key[ind] = '\0';
-        
+
         dev.printf("Please provide the TimeZoneDB API key\n");
         while (!dev.readable()) {
             wait(0.001);
@@ -250,7 +254,7 @@
             wait(0.01);
         }
         time_api_key[ind] = '\0';
-        
+
         dev.printf("Please provide the OpenWeather API key\n");
         while (!dev.readable()) {
             wait(0.001);
@@ -266,10 +270,10 @@
         }
         weather_api_key[ind] = '\0';
 
-        
-        
-        // Because this is a simple proof of concept, we store the password in 
-        // plaintext. It should be noted, however, that you **should never do 
+
+
+        // Because this is a simple proof of concept, we store the password in
+        // plaintext. It should be noted, however, that you **should never do
         // this in "real life"**
         fid = fopen("/local/settings.txt", "w");
         fprintf(fid, "%s\n%s\n%s\n%s\n%s\n", ssid, pass, ip_api_key, time_api_key, weather_api_key);
@@ -287,18 +291,18 @@
 
     // Set up the WiFi Access Point
     dev.printf("Connecting to WiFi %s with Password %s\n", ssid, pass);
-    
+
     res = wifi.connect(ssid, pass);
     if (!res) {
         dev.printf("Connection Failed... Resetting Device\n");
         err_led = 1;
         mbed_reset();
     }
-    
+
     dev.printf("Connected with IP Address: %s\n", wifi.getIPAddress());
-    
+
     /** API REQUESTS **/
-    
+
     int header_ind = 0;
     int footer_ind = 0;
     int read_len = 0;
@@ -307,25 +311,25 @@
 
     TCPSocketConnection tcp;
     tcp.connect("api.ipstack.com", 80);
-    
-    sprintf(cmd, 
-        "GET /check?access_key=%s HTTP/1.1\r\nHost: api.ipstack.com\r\n\r\n",
-        ip_api_key);
+
+    sprintf(cmd,
+            "GET /check?access_key=%s HTTP/1.1\r\nHost: api.ipstack.com\r\n\r\n",
+            ip_api_key);
     tcp.send_all(cmd, strlen(cmd));
-    
+
     wait(5);
-    
+
     read_len = wifi.recv(buffer, BUF_SIZE - 1, 0);
     buffer[read_len] = '\0';
-    
+
     // Cleanup
-    
+
     while (header_ind < read_len) {
         // if we are \r, look ahead to see \n\r\n:
         if(buffer[header_ind] == '\r' &&
-           buffer[header_ind+1] == '\n' &&
-           buffer[header_ind+2] == '\r' &&
-           buffer[header_ind+3] == '\n') {
+                buffer[header_ind+1] == '\n' &&
+                buffer[header_ind+2] == '\r' &&
+                buffer[header_ind+3] == '\n') {
             // Increment header_ind, look for JSON
             // Now just look for {
             header_ind += 4;
@@ -349,7 +353,7 @@
 
     MbedJSONValue parser;
     parse(parser, buffer + header_ind);
-    
+
     latitude =  parser["latitude"].get<double>();
     longitude = parser["longitude"].get<double>();
 
@@ -359,10 +363,10 @@
     time_tcp.connect("api.timezonedb.com", 80);
 
     sprintf(cmd,
-        "GET /v2.1/get-time-zone?key=%s&format=json&by=position&lat=%0.4f&lng=%0.4f HTTP/1.1\r\nHost: api.timezonedb.com\r\n\r\n",
-        time_api_key,
-        latitude,
-        longitude);
+            "GET /v2.1/get-time-zone?key=%s&format=json&by=position&lat=%0.4f&lng=%0.4f HTTP/1.1\r\nHost: api.timezonedb.com\r\n\r\n",
+            time_api_key,
+            latitude,
+            longitude);
 
     time_tcp.send_all(cmd, strlen(cmd));
 
@@ -370,18 +374,18 @@
 
     read_len = wifi.recv(buffer, BUF_SIZE - 1, 0);
     buffer[read_len] = '\0';
-    
+
     // Cleanup
-    
+
     // Clean up front
     // Read through headers (\r\n\r\n)
     header_ind = 0;
     while (header_ind < read_len) {
         // if we are \r, look ahead to see \n\r\n:
         if(buffer[header_ind] == '\r' &&
-           buffer[header_ind+1] == '\n' &&
-           buffer[header_ind+2] == '\r' &&
-           buffer[header_ind+3] == '\n') {
+                buffer[header_ind+1] == '\n' &&
+                buffer[header_ind+2] == '\r' &&
+                buffer[header_ind+3] == '\n') {
             // Increment header_ind, look for JSON
             // Now just look for {
             header_ind += 4;
@@ -403,7 +407,7 @@
         }
     }
     buffer[footer_ind + 1] = '\0';
-    
+
     MbedJSONValue time_parser;
     parse(time_parser, buffer + header_ind);
 
@@ -412,21 +416,21 @@
     set_time(time_parser["timestamp"].get<int>() + 5 + 3);
     // Now that we know what time it is, set up our Time Thread
     time_thread.start(time_updater);
-    
+
     TCPSocketConnection forecast_sck;
 
     forecast_sck.connect("api.openweathermap.org", 80);
 
     sprintf(cmd,
-        "GET /data/2.5/weather?lat=%0.4f&lon=%0.4f&APPID=%s&cnt=8\r\nHost: api.openweathermap.org\r\n\r\n",
-        latitude, longitude, weather_api_key);
+            "GET /data/2.5/weather?lat=%0.4f&lon=%0.4f&APPID=%s&cnt=8\r\nHost: api.openweathermap.org\r\n\r\n",
+            latitude, longitude, weather_api_key);
     forecast_sck.send_all(cmd, strlen(cmd));
 
     wait(5);
 
     read_len wifi.recv(buffer, BUF_SIZE - 1, 0);
     buffer[read_len] = '\0';
-    
+
     // We don't have enough memory for another parser (why?), so just
     // look for the word "temp" 0 hopefully won't have a city named "temp"!
     char* ind = strstr(buffer, "temp");
@@ -453,7 +457,7 @@
     temp = kelvin2farenheit(temp);
     char temp_buf[12];
     sprintf(temp_buf, "   %dF", temp);
-    
+
     lcd_lock.lock();
     uLCD.text_width(2);
     uLCD.text_height(2);
@@ -466,8 +470,8 @@
         // Wait for 60 seconds
         if ((prev_time + 60) < curr_time) {
             sprintf(cmd,
-                "GET /data/2.5/weather?lat=%0.4f&lon=%0.4f&APPID=%s\r\nHost: api.openweathermap.org\r\n\r\n",
-                latitude, longitude, weather_api_key);
+                    "GET /data/2.5/weather?lat=%0.4f&lon=%0.4f&APPID=%s\r\nHost: api.openweathermap.org\r\n\r\n",
+                    latitude, longitude, weather_api_key);
             forecast_sck.connect("api.openweathermap.org", 80);
             wait(10);
             forecast_sck.send_all(cmd, strlen(cmd));
@@ -509,6 +513,7 @@
     }
 }
 
-int main() {
+int main()
+{
     clock_init();
 }