Skip to content

Project 2.3.1: Bluetooth Environmental Alarm

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


Overview

This project combines a BME280 environmental sensor, a buzzer, and BLE monitoring to create a simple environment alarm node.

The Pico reads temperature, humidity, and pressure, then uses threshold logic to decide when to raise an alert.

A similar design could be used in a greenhouse, small storeroom, or equipment cabinet where unsafe climate conditions should be reported quickly.

The final system should show live environmental data, trigger a buzzer when limits are exceeded, and allow the phone to adjust the temperature and humidity thresholds.

Required Components

BME280 sensor module
BME280 sensor module
Phone with BLE app
Phone with BLE app
Raspberry Pi Pico 2 W
Raspberry Pi Pico 2 W
Active buzzer
Active buzzer
Breadboard
Breadboard
Jumper wires
Jumper wires

Circuit Connections

Component terminal Connect to Pico physical pin Notes
BME280 VCC 3.3V Physical pin 36 Sensor power
BME280 GND GND Physical pin 38 Common ground
BME280 SDA GPIO 8 GPIO 8 / physical pin 11 I2C0 SDA
BME280 SCL GPIO 9 GPIO 9 / physical pin 12 I2C0 SCL
Buzzer positive (+) GPIO 18 GPIO 18 / physical pin 24 Use a driver stage if your buzzer requires more current
Buzzer negative (-) GND Physical pin 38 Common ground

Wiring Diagram

Circuit Diagram

  Raspberry Pi Pico 2 W
  ┌─────────────────────┐
  │                     │
  │  GPIO 8  ───────────┤──── BME280 SDA
  │  GPIO 9  ───────────┤──── BME280 SCL
  │                     │
  │  3.3V    ───────────┤──── BME280 VCC
  │  GND     ───────────┤──── BME280 GND
  │                     │
  │  GPIO 18 ───────────┤──── Buzzer (+)
  │  GND     ───────────┤──── Buzzer (-)
  │                     │
  └─────────────────────┘

Step-by-Step Assembly

Step 1: Place the Raspberry Pi Pico 2W

Place the Raspberry Pi Pico 2W on the breadboard so it sits across the center gap. Keep the USB port facing outward so you can easily connect it to your computer.

Step 2: Place the BME280 Sensor

Place the BME280 module on the breadboard or hold it beside the breadboard with jumper wires. Check the printed labels and identify VCC, GND, SDA, and SCL before wiring.

Step 3: Connect BME280 VCC

Connect BME280 VCC to 3.3V.

Step 4: Connect BME280 GND

Connect BME280 GND to GND.

Step 5: Connect SDA to GPIO 8

Connect BME280 SDA to GPIO 8.

Step 6: Connect SCL to GPIO 9

Connect BME280 SCL to GPIO 9.

Step 7: Place the Buzzer

Place the buzzer on the breadboard and identify its positive (+) and negative (-) pins.

Step 8: Connect the Buzzer Positive Pin

Connect the buzzer positive (+) pin to GPIO 18.

Step 9: Connect the Buzzer Negative Pin

Connect the buzzer negative (-) pin to GND.

Step 10: Check the I2C Wires

Make sure SDA and SCL are not crossed before powering the Pico.

Wiring Check

  • [x] Pico 2W is placed correctly across the breadboard center gap
  • [x] BME280 VCC connects to 3.3V
  • [x] BME280 GND connects to GND
  • [x] BME280 SDA connects to GPIO 8
  • [x] BME280 SCL connects to GPIO 9
  • [x] Buzzer positive pin connects to GPIO 18
  • [x] Buzzer negative pin connects to GND
  • [x] No loose jumper wires

Intermediate Note This project uses BLE on the Raspberry Pi Pico 2W. Use a BLE app such as nRF Connect, LightBlue, or a BLE UART terminal to connect to AIDER_EnvAlarm and send commands. If the BME280 is not detected, run an I2C scanner and confirm the SDA and SCL pins before running the full alarm code.


Testing Individual Components

Before running the full project, test each part separately. This makes it easier to find wiring, library, or code problems.

Hardware Setup

  • Build the BME280 I2C wiring first, then add the buzzer
  • Power the sensor from 3.3V and keep the I2C wires short and neat

Test the Input Sensor

  • Run i2c.scan() and confirm that the sensor appears on the bus
  • Run a short BME280 test script and verify that temperature, humidity, and pressure values look reasonable

Test the Output Device

  • Run a simple buzzer beep test
  • Confirm the buzzer makes a short sound without staying on permanently

Test Communication

  • Upload the final code and connect to AIDER_EnvAlarm with the BLE app
  • Send status to request the current readings
  • Send temp 32 or hum 80 to confirm threshold tuning works

Run the Full System

  • Warm the sensor slightly with your hand or adjust thresholds temporarily for a safe classroom test
  • Confirm that the buzzer and BLE alert only trigger when the threshold is crossed
  • Return the thresholds to sensible values after the test

Save the Project

  • Save the working code after confirming the alarm logic and thresholds
  • Record the threshold values you used so you can compare them in later projects

Additional Testing and Calibration Checks

Calibration and tuning notes

  • Compare the BME280 readings with the classroom conditions so you know whether the sensor is behaving normally
  • Start with moderate limits, then temporarily lower them for a safe classroom trigger test
  • Tune the thresholds until the system alerts only when the condition is clearly outside the acceptable range

Quick testing checklist

  • [ ] BME280 is detected on the I2C bus
  • [ ] BME280.py is saved on the Pico
  • [ ] BLE app finds AIDER_EnvAlarm
  • [ ] status shows live environmental readings
  • [ ] Threshold crossing triggers the buzzer and alert message

Full Project Code

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

from machine import I2C, Pin
import bluetooth
import time
import BME280
from ble_uart import BLEUART

DEVICE_NAME = "AIDER_EnvAlarm"
ALARM_COOLDOWN_MS = 15000

i2c = I2C(0, sda=Pin(8), scl=Pin(9), freq=100000)
bme = BME280.BME280(i2c=i2c)
buzzer = Pin(18, Pin.OUT)

ble = bluetooth.BLE()
ble.active(True)
uart = BLEUART(ble, name=DEVICE_NAME)

temp_limit = 32.0
humidity_limit = 80.0
alarm_enabled = True
last_alarm_ms = time.ticks_add(time.ticks_ms(), -ALARM_COOLDOWN_MS)

command_queue = []


def send_line(message):
    print(message)
    uart.write((message + "\n").encode())


def on_rx(data):
    command = data.decode("utf-8").strip().lower()
    if command:
        command_queue.append(command)


def first_number(text):
    digits = ""
    for char in text:
        if char in "-0123456789.":
            digits += char
        elif digits:
            break
    return float(digits)


def alarm_beep():
    for _ in range(2):
        buzzer.on()
        time.sleep_ms(200)
        buzzer.off()
        time.sleep_ms(200)


def read_environment():
    temp_text = bme.temperature
    humidity_text = bme.humidity
    pressure_text = bme.pressure
    temp_c = first_number(temp_text)
    humidity_pct = first_number(humidity_text)
    return temp_text, humidity_text, pressure_text, temp_c, humidity_pct


uart.on_rx(on_rx)
send_line("Bluetooth environmental alarm ready")

while True:
    now = time.ticks_ms()
    temp_text, humidity_text, pressure_text, temp_c, humidity_pct = read_environment()

    alerts = []
    if temp_c > temp_limit:
        alerts.append("HIGH TEMP")
    if humidity_pct > humidity_limit:
        alerts.append("HIGH HUMIDITY")

    if alerts and alarm_enabled and time.ticks_diff(now, last_alarm_ms) >= ALARM_COOLDOWN_MS:
        alarm_beep()
        send_line("ALERT: {}".format(" | ".join(alerts)))
        last_alarm_ms = now

    if command_queue:
        command = command_queue.pop(0)
        if command in ("status", "read"):
            send_line("Temp:{} Hum:{} Press:{}".format(temp_text, humidity_text, pressure_text))
            send_line("Limits: Temp>{}C Hum>{}%".format(temp_limit, humidity_limit))
        elif command == "arm":
            alarm_enabled = True
            send_line("Alarm armed")
        elif command in ("silence", "disarm"):
            alarm_enabled = False
            buzzer.off()
            send_line("Alarm silenced")
        elif command.startswith("temp "):
            temp_limit = float(command.split()[1])
            send_line("Temperature limit set to {}C".format(temp_limit))
        elif command.startswith("hum "):
            humidity_limit = float(command.split()[1])
            send_line("Humidity limit set to {}%".format(humidity_limit))
        elif command == "help":
            send_line("Commands: status, read, arm, silence, disarm, temp <value>, hum <value>, help")
        else:
            send_line("Unknown command. Send help.")

    time.sleep_ms(300)

How the Code Works

Code Section What It Does Why It Matters
BME280 setup Starts the I2C sensor and captures temperature, humidity, and pressure The project needs reliable climate data before it can make decisions
first_number() Converts BME280 text readings into numeric values The code must compare real numbers against threshold limits
alerts list Collects every threshold that has been crossed Allows one message to explain exactly what is wrong
Alarm cooldown Prevents the buzzer from sounding continuously every loop cycle Makes the alarm more realistic and less noisy

Expected Result

The BLE app can show live environmental readings and adjust threshold values. When the temperature or humidity exceeds the configured limit, the buzzer sounds briefly and the phone receives an alert message.


Troubleshooting

Problem Possible cause Solution
No environmental reading appears SDA and SCL are reversed or BME280.py is missing Check GPIO 8 and GPIO 9 wiring and confirm BME280.py is saved on the Pico root folder
Alarm sounds too often The threshold is set too close to normal room conditions Increase the limit values or add more cooldown time after testing
Buzzer is silent The buzzer wiring is wrong or the buzzer needs a driver Verify buzzer polarity and use a transistor driver if the module is not 3.3V-safe
Phone cannot find the BLE device The Pico is not advertising or the BLE helper files are missing Confirm ble_uart.py and ble_advertising.py are saved on the Pico, restart the board, and scan again from nRF Connect or LightBlue
Commands do not change the system state The phone is connected to the wrong service or the command text is different from the expected command Reconnect to the BLE UART service and send the exact command shown in the test section