Introduction: Build a Raspberry Pi SUPER Weather Station

Let's face it, we humans talk about the weather a lot ⛅️. The average person talks about the weather four times a day, for an average of 8 minutes and 21 seconds. Do the math and that totals 10 months of your life that you will spend yapping about the weather. The weather ranks as the #1 go-to topic for conversation starters and uncomfortable silence breakers. If we are going to talk about it that much, we might as well take our weather street cred to a whole new level. This super-fun and easy project will leverage the Internet of Things (IoT) and a Raspberry Pi to do just that.

We are going to build our very own hyper-local weather IoT dashboard, capturing the weather inside and outside our house over time. The next time someone asks you "how about the weather lately?", you will be able to whip out your phone and leave them breathless with your mad weather analysis skillz ☀️.

What you will need to take the course:
1. Raspberry Pi w/ internet connectivity

2. Raspberry Pi SenseHAT

3. A 6" 40-Pin IDE Male to Female Extension Cable (optional for temperature accuracy)

4. An Initial State account

5. That's it!

Project level: Beginner

Approximate time to complete: 20 minutes

Approximate fun factor: Off the charts

In this step-by-step tutorial, you will:
learn how to use the Weatherstack API integration on Initial State to get the local outside weather in your area

- Learn how to use a Raspberry Pi with a Sense HAT (https://www.raspberrypi.org/products/sense-hat/) to capture weather data inside your house

- Build your own personal hyper-local weather dashboard that you can access from any web browser on your laptop or mobile device

- Give your meteorologist a run for their money

Supplies

What you will need to take the course:

1. Raspberry Pi w/ internet connectivity

2. Raspberry Pi SenseHAT

3. A 6" 40-Pin IDE Male to Female Extension Cable (optional for temperature accuracy)

4. An Initial State account

5. That's it!

Step 1: Getting Started

We’ve already put in a lot of the leg work for you putting the code together, and organizing the information. We’ll just need you to make a few adjustments along the way.

To retrieve all of the things we’ve prepared for you, you’ll need to clone the repository from GitHub. Github is an awesome service that allows us to store, revise and manage projects like this. To clone the repository all we need to do is go into our Pi’s terminal, or your computers terminal that’s SSH’d into your pi and type this command:


$ git clone https://github.com/InitialState/wunderground-sensehat.git

Hit enter and you’ll see this information:

pi@raspberrypi ~ $ git clone https://github.com/InitialState/wunderground-sensehat.git

Cloning into 'wunderground-sensehat'...

remote: Counting objects: 28, done.

remote: Total 28 (delta 0), reused 0 (delta 0), pack-reused 28

Unpacking objects: 100% (28/28), done.

Checking connectivity... done.

Once you see this then congrats, you’ve successfully cloned the Github Repo and have all of the necessary files to build your Super Weather Station. Before we move onto the next step, let’s take some time to explore around this directory and learn a few basic command line commands.

Type in the command below into your terminal:

$ ls

This command lists everything that’s available in the directory that you’re currently in. This list shows that our Github Repo has been successfully cloned into our directory under the name “wunderground-sensehat.” Let’s take a look at what’s in that directory. To change directory’s, all you need to do is type “cd” and then type the name of the directory that you wish to go to.

In this case, we’ll type:

$ cd wunderground-sensehat

Once we hit enter, you’ll see that we’re now in the wunderground-sensehat directory. Let’s type ls again to see what files we’ve installed on our pi.

README.md sensehat.py sensehat_wunderground.py wunderground.py

Here we see the we’ve got our readme document, and a couple different python files. Let’s take a look at sensehat.py. Instead of jumping into the file w/ the cd command like we did for directory’s, we’re going to use the nano command. The nano command allows us to open up the nano text editor where we have all of our python code for each segment of this project. Go ahead and type:

$ nano sensehat.py

Here you can see all of the code we’ve prepared for you for this project. We’re not going to make any changes to this document just yet, but feel free to scroll around and see what we’re going to be doing later in this tutorial.

Step 2: Initial State

We want to stream all of our weather data to a cloud service and have that service turn our data into a nice dashboard that we can access from our laptop or mobile device. Our data needs a destination. We will use Initial State as that destination.


Step 1: Register for an Initial State account

Go to https://www.initialstate.com/app#/register/ and create a new account.


Step 2: Install the ISStreamer

Install the Initial State Python module onto your Raspberry Pi: At a command prompt (don’t forget to SSH into your Pi first), run the following command:

$ cd /home/pi/

$ \curl -sSL https://get.initialstate.com/python -o - | sudo bash

Security Note: The above command has some important anatomy that the user should be aware of.

1) There is a preceding \ before curl. This is important to ensure no alias of curl gets run if one was created. This helps mitigate risk of the command doing more than intended.

2) The command is a piped command, so when running, you are piping the output of a script that is being retrieved from https://get.initialstate.com/python into the command sudo bash. This is done to simplify installation, however, it should be noted that https is important here for helping ensure no man-in-the-middle manipulation of the install script, especially since the script is being run with elevated privileges. This is a common way to simplify install and setup, but if you are a little more wary there are some slightly less convenient alternatives: you can break the command out into two steps and investigate the bash script being downloaded from the curl command yourself to insure it's fidelity OR you can follow the pip instructions, you just wont get an automatically generated example script.

Step 3: Make some Automagic

After Step 2 you will see something similar to the following output to the screen:

pi@raspberrypi ~ $ \curl -sSL https://get.initialstate.com/python -o - | sudo bash

Password: Beginning ISStreamer Python Easy Installation!

This may take a couple minutes to install, grab some coffee :)

But don't forget to come back, I'll have questions later!

Found easy_install: setuptools 1.1.6

Found pip: pip 1.5.6 from /Library/Python/2.7/site-packages/pip-1.5.6- py2.7.egg (python 2.7)

pip major version: 1

pip minor version: 5

ISStreamer found, updating...

Requirement already up-to-date: ISStreamer in /Library/Python/2.7/site-packages Cleaning up...

Do you want automagically get an example script? [y/N]

(the output may be different and take longer if you have never installed the Initial State Python streaming module before)

When prompted to automatically get an example script, type y.

This will create a test script that we can run to ensure that we can stream data to Initial State from our Pi. You will be prompted:

Where do you want to save the example? [default: ./is_example.py]:

You can either type a custom local path or hit enter to accept the default. You will be prompted for your username and password that you just created when you registered your Initial State account. Enter both and the installation will complete.

Step 4: Access Keys

Let’s take a look at the example script that was created. Type:

$ nano is_example.py

On line 15, you will see a line that starts with streamer = Streamer(bucket_ .... This lines creates a new data bucket named “Python Stream Example” and is associated with your account. This association happens because of the access_key=”...” parameter on that same line. That long series of letters and numbers is your Initial State account access key. If you go to your Initial State account in your web browser, click on your username in the top right, then go to “my account”, you will find that same access key at the bottom of the page under “Streaming Access Keys”.

Every time you create a data stream, that access key will direct that data stream to your account (so don’t share your key with anyone).

Step 5: Run the Example

Run the test script to make sure we can create a data stream to your Initial State account.

Run the following:

$ python is_example.py

Step 6: Profit

Go back to your Initial State account in your web browser. A new data bucket called “Python Stream Example” should have shown up on the left in your log shelf (you may have to refresh the page). Click on this bucket and then click on the Waves icon to view the test data.

You will want to step through the Waves tutorial to familiarize yourself with how to use this data visualization tool. Next, view the data in Tiles to see this same data in dashboard form.

You are now ready to start streaming real data from Wunderground and more.

Step 3: Sense HAT

The Sense HAT is an add-on board for the Raspberry Pi that is full of sensors, LEDs, and a tiny joystick. What is so great about this little add-on is that it is incredibly easy to install and use thanks to a fantastic Python library that you can quickly install. For this project, we will use the temperature, humidity, and barometric pressure sensors on the Sense HAT. Let's set it up.

The first step in using the Sense HAT is to physically install it onto your Pi. With the Pi powered down, attached the HAT as shown in the image.

Power on your Pi. We need to install the Python library to make it easy to read the sensor values from the Sense HAT. First, you will need to ensure that everything is up-to-date on your version of Raspbian by typing:

$ sudo apt-get update

Next, install the Sense HAT Python library:

$ sudo apt-get install sense-hat

Reboot your Pi.

We are ready to test the Sense HAT by reading sensor data from it and sending that data to Initial State.

Let's test our Sense HAT to make sure everything is working. We will use the script located athttps://github.com/InitialState/wunderground-sensehat/blob/master/sensehat.py. You can copy this script to a file on your Pi or access it from our Github repository that we cloned earlier. Change into your wunderground-sensehat directory and then nano into your sensehat.py file by typing:

$ nano sensehat.py

Notice on the first line that we are importing the SenseHat library into the script. Before you run this script, we need to setup our user parameters.

# --------- User Settings ---------
CITY = "Nashville"

BUCKET_NAME = ":partly_sunny: " + CITY + " Weather"

BUCKET_KEY = "sensehat"

ACCESS_KEY = "Your_Access_Key"

SENSOR_LOCATION_NAME = "Office"

MINUTES_BETWEEN_SENSEHAT_READS = 0.1

# ---------------------------------

Specifically, you need to set your ACCESS_KEY to your Initial State account access key. Notice how easy it is to read data from the Sense HAT in a single line of Python (e.g. sense.get_temperature()).
At a command prompt on your Pi, run the script:

$ sudo python sensehat.py

Go to your Initial State account and view the new data bucket created by the Sense HAT.

Now, we are ready to put it all together and create our hyper-local weather dashboard!

Step 4: Hyper Local Weather Dashboard

The final step in this project is simply combining our Weather Data and our Sense HAT script into a single Dashboard. To do this, we will be using the Initial State Integration with Weatherstack to add weather data into our Sensehat dashboard we created in the last step.

Using the Weatherstack API is super simple. In the past on this tutorial, we had you create and run a script to pull data from a weather data api, but since the inception of this tutorial Initial State has a created the Data Integration Marketplace. The Data Integration Marketplace gives you the power to access and stream API's to an Initial State dashboard with no code. It's literally just a few mouse clicks and BAM: weather data.
On Medium, I've written a more in-depth tutorial on how to use the Weatherstack integration and create weather alerts, but I'll quickly list out how to get started below.

Using The Weatherstack Integration

1. Log into your Initial State account

2. Click the details button on the Weatherstack box on the integrations page. This page will tell you all of the basic information about the integration and what’s required to use it. In this case, you’ll just need a zip code (or latitude & longitude) of a location that you’ll want to monitor the weather for, and you’ll have to know what units you’ll want to see that data in (metric, scientific or US imperial).

3. Click the Begin Setup button and you’ll see a modal pop up from the right side of your screen. There are just a few easy steps to take before we can start watching that weather data roll in:

4. Give your new dashboard a name. I named mine Nashville Weather.Pro tip: I like to use emoji’s in my dashboards names to give them a little more oomph. A quick way to pull up emojis on a Mac is Ctrl+Command+Space bar. For Windows hold the Windows button and either the period (.) or semicolon (;). 2 5.Type in your location. I use the Zip Code of the area I want to track, but you can also put Latitude and Longitude to be more specific. It’s easy to find the latitude and longitude of your area just by going to google maps, searching for a place and then copying the latitude & longitude out of the browser and pasting it into the form. Only US, UK and Canada locations can be used at this time.

6. Choose your units. I chose US/Imperial because I lived in the United States.

7. Choose to create a new bucket or send your Weatherstack data to an existing bucket.In this tutorial, if you've already set up your Sense Hat to stream to Initial State (in the last step) then just send the Weatherstack data to that bucket.

8. Choose whether you want all the data that Weatherstack sends or if you want just specific weather data to send to your dashboard. You can always send all the data and take a few tiles out later.

9. Choose how often you want your dashboard to update with weather conditions. You can choose between every 15 minutes or hour by hour. Keep in mind that sending data every 15 minutes costs an extra token compared to sending it every hour. So, if you’re wanting to use other integrations in the marketplace at the same time then you may want to just poll every hour. You can always stop sending data from the integration and start it again, or change the frequency at which you send data later. However, if you do stop it and start again then there will be gaps in your data.

10. Click Start Integration. Now you’re streaming data from Weatherstack! Click the “View in the IoT App” button to see the first data points roll in.

11. Customize your dashboard. If you’re streaming to a new bucket, we’ve set you up with a template to get you started. However, you should make it your own! Press the down arrow in the top center of your dashboard to bring down the timeline, click Edit Tiles, move some tiles around, resize them and change the background. Make the dashboard the way you want it so that it’s easy for you to ingest the data you want to collect. You can also use other Weatherstack templates that we’ve created for you here. To add a little more context to your dashboard, you can also add a map that shows the location of where you’re monitoring the weather. Your dashboard might look a little bare at first, but give it some time and it will fill up with beautiful historical weather data.

Step 5: Add a Map to Your Dashboard (Bonus)

We can easily add a map tile to our dashboard showing the location of our weather stream. You can learn more about the interactive map view in tiles athttp://support.initialstate.com/knowledgebase/articles/800232-tiles-map-view. We could simply add a new streamer.log statement in our Python script (and I'll explain how you can do that at the end of this section). Instead, we will take this opportunity to show you a different way to send data into your dashboard.

Step 1: Get Your Location's Latitude/Longitude Coordinates

You need to get the latitude/longitude coordinates of your location. One way to do this is to go to Google Maps, search for your location, and zoom in to your exact location. In the URL, you will see your latitude/longitude coordinates. In the example above, my coordinates are 35.925298,-86.8679478.

Copy your coordinates (you will need them in step 2), and make sure you don't accidentally copy any extra characters from the URL.

Step 2: Build a URL to Send Data Into Your Dashboard

Click on the "settings" link under the bucket name in the bucket shelf. This will bring up the screen above. Copy the text in the API Endpoint section and paste it in your favorite text editor. We will use this to build a URL that we can use to send data into our existing bucket and dashboard. In my bucket, the text that I copied looks like: https://groker.initialstate.com/api/events?accessKey=bqHk4F0Jj4j4M4CrhJxEWv6ck3nfZ79o&bucketKey=shwu1 Your URL will have your accessKey and bucketKey. We need to add a stream name and value to the URL parameters to complete the URL.

Add "&MapLocation=YOUR_COORDINATES_FROM_STEP1" to your URL

(insert the coordinates from Step 1, no spaces and don't copy mine!!)

Here's what mine looks like: https://groker.initialstate.com/api/events?accessKey=bqHk4F0Jj4j4M4CrhJxEWv6ck3nfZ79o&bucketKey=shwu1&MapLocation=35.925298,-86.8679478

Paste your complete URL to the address bar of your browser and hit enter (or use the 'curl' command at a command prompt) to send your map coordinates to the stream, "MapLocation", in your new bucket.

If you look at your dashboard in Tiles now (you may have to refresh if you get impatient), a new Tile named MapLocation should have appeared zoomed into your current location.

Step 2 Alternative: Modify Your Script

If you really do not like Step 2 above, you can simply add another streamer.log statement to your Python script. Simply add the line

streamer.log("MapLocation","YOUR_COORDINATES_FROM_STEP1")

somewhere inside the def main(): function of the sensehat_wunderground.py script (pay attention to indentation b/c Python requires you to follow strict indentation rules). For example, I added streamer.log("MapLocation","35.925298,-86.8679478") right after line 138.

Step 6: Fixing the Sense Hat Temperature Reading

You may notice that your Sense HAT's temperature readings seem a bit high - that's because they are. The culprit is the heat generated from the Pi’s CPU heating up the air around the Sense HAT when it is sitting on top of the Pi.

To make the temperature sensor useful, we need to either get the HAT away from the Pi (which would eliminate the important benefit of being a compact solution) or try to calibrate the temperature sensor reading. The CPU is the primary cause of the parasitic heat affecting our temperature sensor, so we need to figure out the correlation. When reviewing the Enviro pHAT for the Pi Zero we came up with an equation to account for the CPU temperature affecting a hat's temperature reading. We just need the CPU temperature and a scaling factor to calculate the calibrated temperature:

temp_calibrated = temp - ((cpu_temp - temp)/FACTOR) 

We can find the factor by recording the actual temperature and solving for it. In order to find the actual temperature in the room, we need a different temperature sensor setup. Using a DHT22 sensor (setup instructions here and script here), we can record and visualize both temperatures simultaneously:

The result reveals that the Sense HAT's reading is off by 5-6 degrees Fahrenheit pretty consistently. Adding the CPU temperature into the mix (with this script), first off shows that it is extremely hot, and second off reveals a sort of wave that the Sense HAT measurement mimics.

After recording for about 24 hours, I solved for the factor using six different readings at six different points in time. Averaging the factor values gave a final factor value of 5.466. Applying the equation

temp_calibrated = temp - ((cpu_temp - temp)/5.466)

the calibrated temperature came to within one degree of the actual temperature reading:

You can run this calibration correction on the Pi itself, inside of the wunderground_sensehat.py script.

Step 7: Bonus: Configure Your Own Weather Alerts

Let's create a SMS alert whenever temperature drops below freezing.

We are going to follow the Trigger notification setup process outlined on the support page.

Make sure your weather data bucket is loaded.

Click on the bucket's settings in the data shelf (under its name).

Click on the Triggers tab.

Select the data stream to trigger on (you can use the drop-down list to select from existing streams once a data bucket has loaded or you can type in the stream name/key manually; *note Safari does not support HTML5 dropdown lists). In my example screenshot above, I selected Temperature(F).

Select the conditional operator, in this case '<'.

Select the Trigger value that will trigger an action (manually type in the desired value). In this case, type in 32 as shown above.

Click the '+' button to add the Trigger condition.

Select the action (current actions available are notify by SMS or email).

Click the '+' button to add the action. Input any verification code if adding a new phone number or email to complete setup.

Your trigger is now live and will fire when the condition is met. Click done to return to the main screen.

PIR SMS

Whenever temperature drops below 32, you will get a text message. You set alerts on anything in your weather data bucket (*note that you need to use emoji tokens, not the actual emojis).

For example, whenever it is raining

:cloud: Weather Conditions = :umbrella: 

Whenever it is windy

:dash: Wind Speed(MPH) > 20 

etc.

Step 8:

Internet of Things Contest 2016

Second Prize in the
Internet of Things Contest 2016

First Time Author Contest 2016

Participated in the
First Time Author Contest 2016