How To Build Your Own Raspberry Pi Weather Station?

Raspberry Pi is an enormously popular single-board computer that’s inexpensive and easy to use and can be used for a huge range of purposes and projects.

How To Build Your Own Raspberry Pi Weather Station?

Our comprehensive “how-to” guide puts together everything you need to know to build your own weather station using Raspberry Pi as its core!

What Is Raspberry Pi?

Raspberry Pi is a credit card-sized computer that is designed to be plugged into a TV or a computer monitor and can be used for a number of purposes, including computer programming, games, music, and using IoT devices. 

Before we take a closer look at the nuances of building your weather station, it is worth taking a look at how it will work. There will be three elements:

  • Your own Raspberry Pi hooked up to a sensor to measure humidity and temperature, via a General Purpose Input/Output Breadboard Extension (GPIO)
  • A Python script – this will read the information collected from your chosen sensor or sensors, and transfer it to an SQLite Database to be stored.
  • An SPA – this is a Single Page Application written in PHO. This can read the data from the data that is collected from your database and make it readable. The code in this section will be reduced thanks to the application being based on the Twig template and the Slim Framework.

What Will I Need?

There are a number of prerequisites that you will need to secure, and these include

  • A Raspberry Pi running Raspberry Pi OS (previously known as Raspbian). This should be powered by a wall adaptor or a USB cable.
  • A DHT11 humidity and temperature sensor – this is usually the cheapest, most accessible option
  • Four jumper wires
  • A GPIO Breadboard
  • 10k Ohm pull-up resistor

Step 1: Connect The DHT11 Sensor To The Raspberry Pi

Once you have gathered all the equipment, it is time to get started.

The first step is to set the DHT11 sensor up with the GPIO Breadboard extension – this will allow the sensor to read properly.

Remove the case from your Raspberry Pi, and connect the T-cobbler to the breadboard.

Join the T-cobbler to the 40-pin cable on one side, and plug the other end of this 40-pin cable into the GPIO pins of the Raspberry Pi.

Next, join your DHT11 sensor into the breadboard, making sure that the top and front face the left side.

Connect the GND of the sensor to a GPIO pin – this will be a white-colored cable – and then join the VCC pin of the sensor to the 3.3v pin – this will be the longer of the green wires.

Join the OUTPUT pin of the sensor to the GPIO 17 pin (the yellow wire), and then join a 10k Ohm pull-up resistor between the VCC and the Output.

Step 2: Set Up The Raspberry Pi

Once your wires are in place, you need to install and configure the software needed for your weather station onto your Raspberry Pi, and there are several packages to include.

You will need to kick things off by running a specific command:

sudo apt-get update
sudo apt-get install -y \
npm \
php8.0-cli \
php8.0-fpm \
php8.0-intl \
php8.0-csalite3 \
python3 pip3 \
nainx \
sqlite3

Following this, ad the pi user to the gpio and www-data groups by running another command:

sudo usermod – uG gpio www-data pi

Change and enable the www-data’s shell by running another command:

sudo usermod – shell/bin/bash www-data

And finally, install Pipeny as follows:

pip3 install – user pipenv

Step 3: Create A Project Directory For The Application

A key element of any Raspberry Pi project is code, and your weather station is no exception to this rule.

Before any code can be written, however, you need to do two things: firstly, create the structure for the project directory, and secondly, change into the top-level directory.

The following code will be required to achieve this:

mkdir – p raspberrypi-weather-station/public/css \
raspberrypi-weather-station/data/ \
raspberrypi-weather-station/ bib \
raspberrypi-weather-station/ templates
cd raspberrypi-weather-station

To summarize, these commands will instruct the creation of a new directory, named raspberry-pi-weather-station, and this will contain four smaller sub-categories:

  • bin – will contain the Python script
  • data – will contain the SQLite database for the application
  • public – will contain the PHO file required to power the PHO app, as well as a directory named css. This will contain the PHO applications CSS file.
  • templates – will contain the Twig template required by the PHP application to render output.

Step 4: Create The Database For The SQLite Application

Once the project directory is created, you need to create the SQLite database for the project – this tends to be the preferred option thanks to ease of configuration, as well as lower overheads.

The schema for the database will consist of one table of three columns:

  • Humidity stores humidity readings
  • Temperature stores temperature readings
  • Timestamp stores time and date of each reading, and will be inserted automatically using the current value.

This database is created with the command:

sqlite3 data/weather_station.sqlite

While the schema is created with another command:

create table weather_data
(
temperature real default 0.0 not null,
humidity real default 0.0 not null.
timestamp DATETIME default CURRENT_TIMESTAMP
);

This process will create the applications SQLite database, and you will be ready to proceed to the next step.

Step 5: Create Python Script To Read DHT11 sSensor

Step 5 includes creating a Python script to read the DHT11 sensor and gather data on humidity and temperature – you will need to first install Adafruit_DHT package to allow the script to work, and this can be achieved with the command:

Next, create the Python script by heading to the bin directory, creating a new file names dht11-sensor-reader.py, and then insert the code:

import Adafruit_DHT
import os
import random
import sqlite3
import time
from sqlite3 import Error
def create_connection(path):
    db_conn = None
    try:
        db_conn = sqlite3.connect(path)
        print(“Connection to SQLite DB successful”)
    except Error as e:
        print(f”The error ‘{e}’ occurred”)
    return db_conn
def execute_query(db_conn, query, query_parameters):
    cursor = db_conn.cursor()
    try:
        cursor.execute(query, query_parameters)
        db_conn.commit()
        print(“Query executed successfully”)
    except Error as e:
        print(f”The error ‘{e}’ occurred”)
gpio_pin = 17
database_file = ‘data/database/weather_station.sqlite’
humidity, temperature = Adafruit_DHT.read_retry(database_file, gpio_pin)
if humidity is not None and temperature is not None:
    connection = create_connection(‘./data/database/weather_station.sqlite’)
    add_weather_data = f’INSERT INTO weather_data (temperature, humidity) VALUES (:temperature, :humidity);’
    parameters = {“temperature”: round(temperature, 2), “humidity”: round(humidity, 2)}
    execute_query(connection, add_weather_data, parameters)

 This process imports the packages, and then creates a connection to the SQLite database, as well as running an SQL query against the database.

Next, the variables are defined, the GPIO pin is stored, and this allows the temperature and humidity to be read, the database to be accessed, and the retrieved sensor data to be written to the database.

Step 6: Generate A Crontab Entry To Allow Python Script To Run

Step 6: Allow Python Script To Run

Once the Python script has been written, you need to create a Cron job – this allows the script to be run regularly and add the data to the database, and can be achieved with the “crontab-e” command to open the Crontab editor.

You can then choose how often you would like to run the script.

As an alternative at this stage, you can also use a specific editor such as Pico or VIM, and will need to follow the specific requirements for each of these.

Step 7: Build The PHP Web App

The next step is to create a PHP application, and this requires installing everything that the app will need.

You can enter this code into Computer to take care of this:

composer install \
    laminas/laminas-db \
    php-di/php-di \
    slim/psr7 \
    slim/slim \
    slim/twig-view \
    twig/intl-extra

Once this is entered, create a new PHP file in the public directory, and name this index.php. Paste code in this file as follows:

<?php
declare(strict_types=1);
use DI\Container;
use Laminas\Db\Adapter\Adapter;
use Laminas\Db\Sql\Sql;
use Psr\Http\Message\{
    ResponseInterface as Response,
ServerRequestInterface as Request
};
use Slim\Factory\AppFactory;
use Slim\Views\{Twig,TwigMiddleware};
use Twig\Extra\Intl\IntlExtension;
require __DIR__ . ‘/../vendor/autoload.php’;
$container = new Container();
$container->set(‘view’, function(\Psr\Container\ContainerInterface $container) {
    $twig = Twig::create(__DIR__ . ‘/../resources/templates’);
    $twig->addExtension(new IntlExtension());
    return $twig;
});
$container->set(‘weatherData’, function() {
    $dbAdapter = new Adapter([
        ‘driver’ => ‘Pdo_Sqlite’,
        ‘database’ => __DIR__ . ‘/../data/database/weather_station_test_data.sqlite’
    ]);
    $sql = new Sql($dbAdapter, ‘weather_data’);
    $select = $sql
        ->select()
        ->columns([‘temperature’, ‘humidity’, ‘timestamp’]);
    return $dbAdapter->query(
        $sql->buildSqlString($select),
        $dbAdapter::QUERY_MODE_EXECUTE
    );
});
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->add(TwigMiddleware::createFromContainer($app));
$app->map([‘GET’], ‘/’, function (Request $request, Response $response, array $args) {
    return $this->get(‘view’)->render(
        $response,
        ‘index.html.twig’,
        [‘items’ => $this->get(‘weatherData’)]
    );
});
$app->run();

This will import the required classes, initialize the Dependency Injection Container, and register the services “view” and “weatherData”, which retrieve templates for formatting and connecting to the SQLite Database respectively.

This allows a SQL query to be generated to select records from the table you created earlier, runs the query, and stores the results. 

Step 8: Create The View Template

Next, create a view template to allow data to be presented professionally – this is created in the resources/templates directory, in a fresh file titled index.html.twig, to which this code is added:

<!doctype html>
<html lang=”en”>
<head>
    <meta charset=”UTF-8″>
    <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
    <link href=”/css/styles.css” rel=”stylesheet”>
    <title>DIY Weather Station</title>
</head>
<body>
<h1 class=”mb-4″>DIY Weather Station</h1>
<div>
    <table>
        <thead>
        <tr>
            <th>Date</th>
            <th>Time</th>
            <th>Temperature (&deg;C)</th>
            <th>Humidity (%)</th>
        </tr>
        </thead>
        <tbody>
            {% for item in items %}
            <tr>
                <td>{{ item.date|format_date() }}</td>
                <td>{{ item.time|format_time(pattern=’hh:mm’) }}</td>
                <td>{{ item.temperature|format_number({rounding_mode: ‘floor’, fraction_digit: 2}, locale=’de’) }}</td>
                <td>{{ item.humidity|format_number({rounding_mode: ‘floor’, fraction_digit: 2}, locale=’de’) }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
</div>
</body>
</html>

This imports stylesheets and essentially helps your data to appear in a clear, accessible manner.

Step 9: Generate A Virtual Host

You are now almost ready to start enjoying your weather station – but you first need to ensure that a virtual host is added to NGINX.

Add a new file to /etc/nginx/sites-available, and name this weather_station, before adding the code:

server {
    listen 80 default_server;
    root /home/pi/raspberrypi-weather-station/public;
    index index.php;
    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;
    location / {
        try_files $uri $uri/ /index.php;
    }
    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass unix:<<X>>.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

The configuration we have included above specifies the location of the web server’s document root (the place where the web server looks for files), which is /var/www/web server/public.

It then asks the system look for an index.html file there. The final step is to enable the correct configuration using this command:

sudo rm /etc/nginx/sites-enabled/default
sudo ln -s /etc/nginx/sites-enabled/weather_station /etc/nginx/sites-enabled/default
sudo systemctl restart nginx

Step 10: Test Out Your Station

Once the process is complete, and if all has gone to plan, you will have a working weather station!

To test, head to http://<<Raspberry Pi iP Address>> to your browser (use the IP address attached to your Raspberry Pi instead of the placeholder), and check out the results!

buy raspberry pi accessories

Final Thoughts

Raspberry Pi is a brilliant tool that can help you create all sorts of amazing projects – including your very own weather station.

With our top tips, you will be on your way to recording the amazing nuances of weather in no time.

Erik D

Leave a Comment

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