Chuyển đến nội dung

Bài 27 · Projects

Project: A Weather Station with Logging and Averages

Build a Raspberry Pi weather station: read a BME280 over I2C, calibrate and smooth values, store readings in SQLite, and compute hourly averages and min/max.

A weather station is the classic first Pi project because it touches every skill at once: reading a sensor, timing a loop, storing data, and turning raw numbers into something useful. Our design is small enough to finish in an evening and solid enough to run for months: one sensor, one Python program, one SQLite database, one systemd service.

The BME280 sensor cannot be attached to this website, so hardware code is read-only. Everything else (the data model, the averaging, the database queries, the outlier filter) is written in Python you can run here with a simulated sensor. Replace the simulator with the real read function and the rest works unchanged.

What you need

  • Any Raspberry Pi with Raspberry Pi OS and I2C enabled (sudo raspi-config, Interface Options).
  • A BME280 breakout (temperature, humidity, pressure). Wire 3.3 V to VIN, GND to GND, SDA to GPIO 2 (pin 3), SCL to GPIO 3 (pin 5).
  • Optional: a case that keeps the sensor away from the Pi's own heat, since a CPU warms the air next to it.

Check the sensor is visible on the bus:

Terminal
sudo apt install i2c-tools python3-smbus
i2cdetect -y 1        # expect 76 or 77 in the grid

The reading code

With the Adafruit library (pip install into a virtual environment, as described in the earlier chapters) a reading is three lines:

Python
import board, adafruit_bme280.basic as bme280

i2c = board.I2C()
sensor = bme280.Adafruit_BME280_I2C(i2c, address=0x76)
print(sensor.temperature, sensor.relative_humidity, sensor.pressure)

Wrap it in a function that returns a dictionary, so the rest of the program never cares where the numbers come from. For this lesson we use a simulated source with the same shape:

Python A simulated sensor with the same interface

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Storing readings in SQLite

SQLite is a database in a single file, with Python support built in. It beats a CSV when you want queries ("average per hour"), survives crashes without a half-written line, and lets two programs read while one writes. This block builds the table and inserts a day of simulated readings, one every 10 minutes, in an in-memory database (use a path like /home/ana/weather/weather.db on the Pi).

Python Create the table and insert a day of data

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always use ? placeholders instead of formatting values into the SQL string. It prevents injection and handles quoting for you.

Filtering bad readings

Real sensors occasionally return a wild value (an I2C glitch, a cable wiggle). Before storing, reject numbers outside physical limits and smooth with a median of the last few samples, which ignores single spikes better than an average.

Python Reject glitches and smooth with a median

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The 85.9 passes the range test but the median keeps the line smooth; it would still be recorded raw in the database, so the better design stores both raw and smoothed values when debugging a sensor.

The main loop

Put it all together. Sleep for a fixed interval, handle errors without exiting, and log what happens:

Python
import sqlite3, time, traceback

DB = "/home/ana/weather/weather.db"
INTERVAL = 600   # seconds

def main():
    db = sqlite3.connect(DB)
    db.execute("CREATE TABLE IF NOT EXISTS readings (ts TEXT, temp_c REAL, humidity REAL, pressure_hpa REAL)")
    while True:
        try:
            r = read_real_sensor()
            if valid(r):
                db.execute("INSERT INTO readings VALUES (datetime('now'),?,?,?)",
                           (r["temp_c"], r["humidity"], r["pressure_hpa"]))
                db.commit()
        except OSError:
            traceback.print_exc()       # goes to the journal
        time.sleep(INTERVAL)

main()

Store timestamps in UTC (datetime('now') is UTC) and convert for display. Run this as a systemd service so it starts at boot and restarts after an I2C error. Check it with sqlite3 weather.db "SELECT * FROM readings ORDER BY ts DESC LIMIT 5;".

flowchart LR
    A["BME280"] -->|"I2C"| B["read_sensor()"]
    B --> C["validate and smooth"]
    C --> D["SQLite file"]
    D --> E["Web page or chart"]

From sensor to storage: each step has one job.

Making it useful

  • Calibration: compare against a trusted thermometer for a day. If yours reads 1.2 degrees warm, subtract an offset in one constant.
  • Placement: shade and ventilation matter more than the sensor. Mount it outdoors in a radiation shield, away from walls.
  • Dashboard: expose /api/latest and /api/hourly with the web server lesson, or publish values over MQTT.
  • Retention: at one reading per 10 minutes you add about 52,000 rows a year, which is tiny. Even so, plan to delete or aggregate old rows if you sample faster.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why use ? placeholders in SQLite statements?

    The driver passes values separately from the SQL text, so they cannot change the query.
  2. 2. Which smoothing method best ignores one-off spikes?

    A median is not pulled by a single extreme value.
  3. 3. On which pins does I2C live on a Pi (BCM numbering)?

    Bus 1 uses GPIO 2 for SDA and GPIO 3 for SCL (physical pins 3 and 5).
  4. 4. Why store timestamps in UTC?

    UTC has no clock changes; convert to local time only when showing data.

Summary

  • Isolate the sensor behind one function that returns a dictionary.
  • Validate against physical limits and smooth with a median.
  • Store readings in SQLite with UTC timestamps and parameterized inserts.
  • Run the loop as a service that survives errors and reboots.
  • Calibrate and place the sensor carefully; it matters more than code.

Next: Project: A Motion-Detecting Alarm

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.