Hear the Story Behind Tomorrow.io’s Historic Launch: Watch “6 Years to Launch” Now”

X
Gareth Goh
Gareth Goh
Apr 29, 2023· 7 min, 38 sec
Gareth Goh
Gareth Goh
Gareth Goh is a product marketing manager at Tomorrow.io, working on the company's enterprise and SMB products. He previously worked at DataRobot, an AI startup, and InsightSquared, a sales analytics startup, in the Boston area. When he isn't diving into weather technology he enjoys spending time with his young baby and watching sports.

How To Create a GUI Weather Widget for Raspberry Pi with a Weather API

Summary

  • Tomorrow.io’s Weather API makes it easy to create a weather widget for Raspberry Pi using Python.
  • The process to create a weather widget for Raspberry Pi includes:
    • Using GUIs in Python (which are lightweight and easy to build)
    • Sending a request every 80 seconds to get the weather data at regular intervals
    • Using the guizero module to can pass your own data through and reflect the current weather values
    • Customizing the widget to your liking

Development boards have experienced significant advancements in recent years, transforming into powerful devices that can function as compact personal computers. One prime example of this evolution is the Raspberry Pi, a versatile single-board computer that has garnered immense popularity among hobbyists, educators, and developers.

Initially designed to promote computer science education, the Raspberry Pi has evolved into a multipurpose platform capable of handling tasks such as web browsing, document editing, and weather forecasting when used to create a weather widget.

The Raspberry Pi’s affordability, low power consumption, and extensive community support make it a great option for a wide range of projects, from simple automation tasks to complex robotics and IoT applications. With each new iteration, the Raspberry Pi continues to offer enhanced performance and functionality, further expanding its potential use cases and inspiring creativity among its growing user base.

Because of this, an easy project to start with when exploring using Raspberry Pi is to create a weather widget using Python, with support from the Tomorrow.io weather API. GUIs in Python are very lightweight and easy to build so they are perfect for a small computer like Raspberry Pi.

If you’re looking for a step-by-step guide on how to build this widget with Raspberry Pi, you’ve come to the right place.

In the following sections, we’ll outline setting up Raspberry Pi, how to get started with acquiring the necessary weather data, and how to integrate.

What Is a Raspberry Pi Weather Station?

A Raspberry Pi weather station is a device that uses a Raspberry Pi computer, weather accessories, and software to measure and record various types of weather data. This can include temperature, humidity, wind speed, air pressure, and other environmental measures. The data collected can then be used to create forecasts or generate alerts for dangerous conditions.

The Raspberry Pi weather station is an excellent way to learn about programming and furthers what you can do with Raspberry Pi weather displays.

If you’re looking for a step-by-step guide on how to build a weather widget with Raspberry Pi, you’ve come to the right place.

In the following sections, we’ll outline setting up Raspberry Pi, how to get started with acquiring the necessary weather data, and how to integrate.

Part I – Weather Data Acquisition and Integration

To get started, you’ll need to ensure you have a weather API key from Tomorrow.io. With your personal weather API you’ll be able to retrieve accurate, hyperlocal weather data for your Raspberry Pi weather widget.

Getting your weather API is easy to do!  Follow these steps:

  1. Sign up for an account with Tomorrow.io in order to get your free weather API key.
  2. Tell us what kind of project you’re doing: After you sign up for an account, a screen will prompt you to share what kind of project using the API for.
  3. Get your API key: Once you have created an account, you will automatically get your free weather API key right in the Tomorrow.io platform. Simply click on the “Development” icon in the navigation, then reveal your key.

We recommend you read our weather API documentation that explains more about our API and where you can find sample code to get started.

Once you’ve grabbed your API key from the Tomorrow.io Weather API, it’s time to get coding and get the weather data we want—temperature and humidity measured each minute in metric values—with the help of Python. Start by placing the following code in a new .py file (weather_widget.py)

import requests 
import threading, time
from string import Template

n this project, we will require the packages above to facilitate weather data acquisition. These packages will enable us to send a request at regular intervals of 80 seconds, to obtain the latest weather information. Our first step is to create a function that can effectively make this request and retrieve the most up-to-date weather forecast data.

def get_weather_data(lat,lon,apiKey):
    URL = Template('https://data.tomorrow.io/v4/timelines?location=$lat,$lon&apikey=$apiKey&fields=temperature&fields=humidity&timesteps=1m')
    r = requests.get(url = URL.substitute(lat=lat,lon=lon,apiKey=apiKey)) 
    data = r.json() 
    return data['data']['timelines'][0]['intervals'][0]

This function fetches weather data for a specified location (latitude and longitude) and returns the first interval of the first timeline, which should contain the current weather data (temperature and humidity) for that location.

If we call this function and enter the (latitude, longitude,) and our API key, print(get_weather_data(45.6427,25.5887,’your_api_key’)), then we should see the following output:

{‘startTime’: ‘2021-03-06T08:31:00Z’, ‘values’: {‘temperature’: -1.66, ‘humidity’: 84.62}}

Obtaining accurate weather data is crucial for this project, and to ensure the widget stays updated, we need to retrieve this information at consistent intervals. As a result, we’ll need to continuously run this function to maintain accurate weather data on the widget.

To do this, we need to update our code with the following snippet:

def update_every_n_seconds(n=80):

    while True:
        weather_data = get_weather_data(45.6427,25.5887,'your_api_key')

        time.sleep(n)

thread = threading.Thread(target=update_every_n_seconds, daemon=True)
thread.start()

Here, you can pass your own data through the function get_weather_data.

Part II – The Widget

To create a widget we will use the guizero module. Guizero is designed to allow new learners, and anyone who needs a starter’s recap to quickly and easily create GUIs for their programs. In this case a GUI weather widget for Raspberry Pi with a weather API.

To get started with guizero you’ll need to install it. Installing it is as easy as downloading and unzipping a file—no special permissions or administrator rights are required.

To install it you can use the pip command: pip install guizero. Once installed, update the imports at the top with the following code:

app =App(title="Weather Widget", width=400, height=100)
temperature_msg = Text(app, text="")
humidity_msg = Text(app, text="")

These lines will create a new widget weather application with the title “Weather Widget” and will declare 2 text placeholders in which we will show the temperature and the humidity.

Lastly, to show this widget at the very end of our file, call the display() method.

app.display()

If we run our program now from the terminal using the command: python weather_widget.py

we should see something like this:

You can see that we only have the title, the content section is blank. That’s because the variables declared above are currently in an empty string. Within the update_every_n_seconds function, we need to update their values to reflect the current weather values.

For this, we need to update the update_every_n_seconds function with the following code snippet:

 def update_every_n_seconds(n=80):
    while True:
        weather_data = get_weather_data(45.6427,25.5887,'your_api_key')
        
        temperature_msg.value = "Temperature: " + str(weather_data['values']['temperature']) + '   °C'
        humidity_msg.value = 'Humidity: ' + str(weather_data['values']['humidity']) + '%'

        time.sleep(n)

In this section of our weather widget project with Raspberry Pi, we will create a function called update_every_n_seconds that continuously updates the weather data at regular intervals.

By default, our function will update the data every 80 seconds, but this interval can be customized by providing a different value for the n parameter. Inside the function, we use an infinite loop to call the get_weather_data function, passing in the latitude, longitude, and API key to retrieve the current weather data.

We then update the temperature and humidity messages with the latest values extracted from the weather data, converting them into strings with appropriate units (‘°C’ for temperature and ‘%’ for humidity).

Finally, we pause the loop for n seconds before proceeding to the next iteration, ensuring that our widget remains updated with the latest weather information at our desired interval.

Using the above code and knowing how this will change the weather application, if we run our program again now we should be able to see the temperature and humidity displayed as weather data in the weather application

Diving into Raspberry Pi and GUIs is a breeze when you have the right tools to get accurate weather updates for your weather widget. With endless customization options for your weather widget, you can incorporate images and leverage the fact that the Tomorrow.io API provides a weather code. Utilize this code to determine the best image to preview based on current weather conditions for your selected zip code. Raspberry Pi offers a versatile platform for creating the most innovative projects, making it an ideal choice for enthusiasts and developers alike who want to create weather apps.

Find Out How Much Weather is Costing You & Start Adapting Today