Raspberry Pi Pico – BME280 Interface on I2C Bus

Raspberry Pi Pico: BME280 Interface on I2C Bus - MicroPython

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

  1. 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

  1. Initialize I2C: This code sets up the I2C connection with GP5 (SCL) and GP4 (SDA) on the Pico.
  2. Initialize BME280: The bme280.BME280(i2c=i2c) line initializes the sensor with the specified I2C connection.
  3. 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.
  4. Print the Data: The print() statements output temperature, pressure, and humidity data to the serial console.

Running the Code

  1. Save the Script as main.py if you want it to run on boot.
  2. Run the Script in Thonny or connect via a serial terminal to see the output on the console.
  3. 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

Leave a Reply

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