🛠 Lire un capteur I2C (BME280 température/humidité)

Raspberry Pi 5 (model-5) · intermediaire · Schéma : IMG-model-5-intermediaire-2-model5-i2-i2c-capteur.svg — Capteur BME280 sur le bus I2C0 : SDA sur GPIO2 (broche 3), SCL sur GPIO3 (broche 5), 3V3 et GND

Objectives

Enable the I2C bus on the Raspberry Pi 5, detect a BME280 environmental sensor (temperature, humidity, pressure), and read its measurements in Python. On the Pi 5, I2C is provided by the RP1 chip; the main I2C0 bus is on GPIO2 (SDA, physical pin 3) and GPIO3 (SCL, physical pin 5).

Hardware

Complete Code

# 1) Activer I2C : sudo raspi-config -> Interface Interfacing Options -> I2C
#    ou dans /boot/firmware/config.txt : dtparam=i2c_arm=on
sudo apt install -y i2c-tools python3-smbus
sudo reboot

# 2) Vérifier la présence du capteur (0x76 ou 0x77 attendu)
i2cdetect -y 1
#!/usr/bin/env python3
# lire_bme280.py — lecture brute des registres du BME280 sur I2C bus 1
import smbus, time

BUS = smbus.SMBus(1)
ADDR = 0x76   # 0x77 si les broches SD0/AD0 sont câblées autrement

def read_regs(reg, n):
    return BUS.read_i2c_block_data(ADDR, reg, n)

# Calibration (une seule fois au démarrage)
dig = read_regs(0x88, 24) + read_regs(0xE0, 7)
BUS.write_byte_data(ADDR, 0xF2, 0x01)              # oversampling humidité
BUS.write_byte_data(ADDR, 0xF4, 0x27)              # mode normal
BUS.write_byte_data(ADDR, 0xF5, 0x00)
time.sleep(0.5)

while True:
    data = read_regs(0xF7, 8)                       # T, P, H bruts
    print("octets bruts T/P/H :", [hex(b) for b in data])
    time.sleep(2)

Expected Verification

i2cdetect -y 1 displays a box at 76 (or 77). The script displays the raw bytes read from the sensor every 2 seconds; using the adafruit-circuitpython-bme280 library, you directly get temperature in °C, humidity in %, and pressure in hPa.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials