To connect a Raspberry Pi Pico to a BME280 sensor over I2C and print temperature, humidity, and pressure to the console, you’ll need to wire the sensor correctly and then use a MicroPython script to read and display the sensor data.
Step 1: Connect the BME280 Sensor to the Pico
- Wiring (assuming default I2C pins on the Pico):
- VCC on BME280 to 3.3V on Pico
- GND on BME280 to GND on Pico
- SCL on BME280 to GP5 on Pico (default I2C0 SCL)
- SDA on BME280 to GP4 on Pico (default I2C0 SDA)
Step 2: Install the BME280 Driver
Go to Tool > Package Manager in Thonny.
Search Micropython-bme280 drivers.
Select the package and Click Instal.
Step 3: MicroPython Script to Read Data from BME280
Here’s the MicroPython script to read temperature, humidity, and pressure from the BME280 and print them on the serial console:
from machine import I2C, Pin
import time
import bme280 # Make sure you have the bme280.py driver saved on the Pico
# Initialize I2C
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=100000) # Using I2C0 with GP5 as SCL and GP4 as SDA
# Initialize BME280
sensor = bme280.BME280(i2c=i2c)
# Read and print sensor data
while True:
temp, pressure, humidity = sensor.read_compensated_data()
# Convert values to standard units
temperature = temp / 100 # Convert to Celsius
pressure = pressure / 25600 # Convert to hPa
humidity = humidity / 1024 # Convert to %RH
print("Temperature:", temperature, "°C")
print("Pressure:", pressure, "hPa")
print("Humidity:", humidity, "%")
print("----------------------------------")
time.sleep(2) # Delay between readings
Explanation of the Script
- Initialize I2C: This code sets up the I2C connection with GP5 (SCL) and GP4 (SDA) on the Pico.
- Initialize BME280: The
bme280.BME280(i2c=i2c)
line initializes the sensor with the specified I2C connection. - Read Sensor Data:
sensor.read_compensated_data()
returns raw sensor data. We convert these values to Celsius for temperature, hPa for pressure, and %RH for humidity. - Print the Data: The
print()
statements output temperature, pressure, and humidity data to the serial console.
Running the Code
- Save the Script as
main.py
if you want it to run on boot. - Run the Script in Thonny or connect via a serial terminal to see the output on the console.
- The temperature, pressure, and humidity will be printed every 2 seconds.
Output on Thonny Shell.
We can also use Putty or other Serail Monitor Software to see this out. By Setting COM Port and Baud Rate @ 115200