Skip to content

Project 3.9.24: Smart Environmental Analytics Engine

Advanced Embedded Systems Project Using Raspberry Pi Pico 2 W and MicroPython

Overview

The Pico tracks environmental readings over time, computes rolling averages, and flags unusual changes.

Environmental measurements are hard to interpret when users see only the newest reading and not the recent trend behind it.

A Pico 2 W prototype with an MQ-5 Liquefied Petroleum/Methane Gas Sensor, BME280, and OLED analytics dashboard.

Rolling averages, anomaly-style detection, and honest local analytics rather than a cloud analytics engine.

Required Components

Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Gas sensor
Gas sensor
Breadboard
Breadboard
Jumper wires
Jumper wires
BME280
BME280
OLED
OLED
---

Circuit Connections

Component terminal Connect to Pico physical pin Notes
MQ-5 AO GPIO 26 ADC0 GPIO 26 / physical pin 31 LPG/methane gas proxy input
BME280 VCC 3.3V output Physical pin 36 Sensor power
BME280 GND GND Physical pin 38 Common ground
BME280 SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA shared with OLED if present
BME280 SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL shared with OLED if present
OLED SDA GPIO 20 GPIO 20 / physical pin 26 I2C0 SDA
OLED SCL GPIO 21 GPIO 21 / physical pin 27 I2C0 SCL
---

Wiring Diagram

Circuit Diagram

MQ-5 AO -> GPIO 26
BME280 SDA -> GPIO 20
BME280 SCL -> GPIO 21
GPIO 20 -> OLED SDA
GPIO 21 -> OLED SCL
Common GND -> MQ-5, BME280, and OLED
BME280 VCC -> 3.3V
BME280 GND -> GND

Diagram Placeholder [Insert wiring diagram or breadboard image here]


Step-by-Step Assembly

  1. Connect the MQ-5 analog output to GPIO 26 through a safe ADC path.
  2. Connect the BME280 to Pico 3.3V, GND, GPIO 20 (SDA), and GPIO 21 (SCL).
  3. Connect the OLED to Pico 3.3V, GND, GPIO 20, and GPIO 21.
  4. Upload ssd1306.py and confirm it appears on the Pico before running the dashboard.
  5. Warm up the MQ-5 and establish a stable room baseline before interpreting analytics labels.

Testing Individual Components

Before running the full project, test each subsystem separately. This makes it easier to find wiring, library, or logic problems before full integration.

  1. Hardware setup: Assemble the Pico, sensor, indicator, and load wiring exactly as shown in the connection table before applying power.
  2. Test the input sensor: Test the MQ-5 and BME280 separately so the analytics history starts with believable readings.
  3. Test the output device: Run an OLED hello-world test before adding the analytics logic.
  4. Test the decision logic: Change gas or temperature gradually and then sharply so you can compare RISING versus ANOMALY behavior.
  5. Run the full system: Run the full analytics engine and compare current values with the rolling averages printed in the Shell.
  6. Validate the prototype: Discuss how the history length changes the sensitivity of anomaly detection.
  7. Save the project: Save the validated program on the Pico as main.py and keep a copy on the computer for future edits.

Full Project Code

After completing and checking the circuit connections, open Thonny IDE, copy and paste this code into a new file or upload the project file to the Raspberry Pi Pico 2 W, then run it from Thonny.

Upload and run this code after the individual tests work correctly.

from machine import ADC, I2C, Pin
import bme280
import time

try:
    from ssd1306 import SSD1306_I2C
    HAS_OLED = True
except ImportError:
    HAS_OLED = False

GAS_PIN = 26
BME_SDA_PIN = 20
BME_SCL_PIN = 21
I2C_SDA_PIN = 20
I2C_SCL_PIN = 21
HISTORY_LENGTH = 6

mq5 = ADC(GAS_PIN)
i2c = I2C(0, sda=Pin(BME_SDA_PIN), scl=Pin(BME_SCL_PIN), freq=400000)
climate = bme280.BME280(i2c=i2c)
if HAS_OLED:
    oled = SSD1306_I2C(128, 64, i2c)

gas_history = []
temp_history = []
hum_history = []


def average(values):
    return sum(values) / len(values) if values else 0


print('Smart environmental analytics engine ready')

while True:
    gas_value = mq5.read_u16()
    try:
        values = climate.values
        temperature = float(values[0].replace('C', ''))
        pressure = float(values[1].replace('hPa', ''))
        humidity = float(values[2].replace('%', ''))
    except Exception:
        temperature = 0
        pressure = 0
        humidity = 0

    gas_history.append(gas_value)
    temp_history.append(temperature)
    hum_history.append(humidity)
    gas_history = gas_history[-HISTORY_LENGTH:]
    temp_history = temp_history[-HISTORY_LENGTH:]
    hum_history = hum_history[-HISTORY_LENGTH:]

    avg_gas = average(gas_history)
    avg_temp = average(temp_history)
    avg_hum = average(hum_history)

    if len(gas_history) >= 3 and (gas_value - avg_gas >= 6000 or temperature - avg_temp >= 4):
        label = 'ANOMALY'
    elif gas_value > avg_gas + 2000 or temperature > avg_temp + 1:
        label = 'RISING'
    else:
        label = 'STABLE'

    print('Gas:{} AvgG:{:.0f} Temp:{} AvgT:{:.1f} Hum:{} AvgH:{:.1f} Label:{}'.format(gas_value, avg_gas, temperature, avg_temp, humidity, avg_hum, label))

    if HAS_OLED:
        oled.fill(0)
        oled.text('Env Analytics', 0, 0)
        oled.text('G:{} A:{:.0f}'.format(gas_value, avg_gas), 0, 16)
        oled.text('T:{} H:{}'.format(temperature, humidity), 0, 32)
        oled.text(label[:16], 0, 50)
        oled.show()

    time.sleep(3)

How the Code Works

Code Section What It Does Why It Matters What to Modify During Testing
History buffers Stores recent gas, temperature, and humidity readings. Analytics depends on recent context rather than only the latest number. Increase or decrease HISTORY_LENGTH to change how stable the averages feel.
Rolling averages Calculates the average baseline for each environmental signal. Averages give the user a trend reference for the latest reading. Watch how the average changes during gradual versus sudden test conditions.
Anomaly logic Compares the newest reading against the recent average and labels the result. This is the local analytics behavior promised by the project title. Tune the anomaly deltas after repeated tests in your own room.

Expected Result

The dashboard shows current environmental readings together with a trend or anomaly label.

Gradual change tends to produce RISING while sharp change produces ANOMALY after the history window fills.

The rolling averages make it easier to explain why the label changed.

Validation Checks

  • Normal condition test: let the room remain stable and confirm the label becomes STABLE.
  • Trend test: create a gradual temperature or gas increase and confirm the label changes to RISING.
  • Anomaly test: create a sharper change and confirm the label changes to ANOMALY.
  • Calibration test: warm up the MQ-5 before collecting any baseline values.
  • Sensitivity test: adjust the history length and compare how quickly the labels change.

Deployment and Limitations

  • This prototype works well for classroom demonstrations and local monitoring pilots.
  • Before deployment, it needs calibration records, protective mounting, and regular validation checks.
  • Display-only systems still depend on correct sensor placement and trained users.

Troubleshooting

Problem Possible Cause Solution
The label is always anomaly The thresholds are too sensitive or the gas sensor has not stabilized Allow more warm-up time and increase the anomaly threshold after observing a baseline.
The averages never change The history is not updating or the room conditions are too static Print the history length and vary the environment more clearly during testing.
Climate values stay at zero The BME280 read failed Test the BME280 separately and shorten the wiring if needed.
OLED is blank The library or I2C wiring is wrong Confirm ssd1306.py is present and verify GPIO 20 and GPIO 21.