Real-Time Weather with Raspberry Pi 4

View current weather data by using the OpenWeatherMap API along with the new Raspberry Pi 4.

Premise

Gathering real-time weather data that has a lot of detail for a project can be difficult. Several web APIs exist, but many require payment use, or are complicated to set up. Thankfully, OpenWeatherMap.org has an amazing API for individuals that is both free and simple. Just select a service, generate an API key, and send requests! Then, use that data to create displays, change the state of a machine, or even control other devices.

Configuring OpenWeatherMap

Upon entering the site, first create a new account.

After signing in, navigate to the API page at the top to view their wide variety of weather APIs. Click the “Subscribe” button under the “Current Weather Data” section.

This is the API that is available for free. At this tier, users are limited to 1 request per second, which should be plenty for a single project. The free tier also has a 5-day/3-hour forecast option and weather alerts. Select the “Get API key and Start” button to go to the next page.

When you register, an email is sent that contains a key. Make sure to allow a few hours for it to become active before using it. After the key is active, copy and paste it into the attached Python code.

Sending Requests

There are four main ways to get the current weather in an API call: by city name, city ID, geographic coordinates, and ZIP code. The attached Python program gets data by sending this GET request:

http://api.openweathermap.org/data/2.5/weather?appid=<KEY>&zip=<ZIP>,<COUNTRY>&units=<UNIT>  

It contains 4 fields that correspond to the API key, ZIP code, 2-letter country code, and the specified unit for temperature.

Another way to get current weather data is to search by city name. This will return data for one city, so searching for a “Springfield” will most likely return data for the wrong city. That is why it is recommended to use either the city ID or ZIP code when gathering data.

Parsing and Using Data

The Python program uses the requests library to send a GET request to the OpenWeatherMap API and returns the response. Since the response is in JSON format, it is necessary to use.json() to convert the string into a Python dictionary.

Now, parameters can be retrieved by using keys to access their corresponding values. Here is an example of a response for the city of London, UK:

Source: Real-Time Weather with Raspberry Pi 4


About The Author

Muhammad Bilal

I am highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top