🛠 Lire un capteur I2C (BME280 température/humidité)
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
- Raspberry Pi 5 running 64-bit Raspberry Pi OS
- BME280 sensor in an I2C module (address 0x76 or 0x77)
- Dupont cables: SDA to pin 3, SCL to pin 5, VCC to 3V3 (pin 1 or 17), GND to pin 6
- The module has built-in pull-up resistors; the pins operate at 3.3 V logic levels
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
- I2C not enabled:
i2cdetect -llists no buses; enable it via raspi-config and then reboot. - Wrong bus number: on Raspberry Pi OS, the user bus is 1 (
/dev/i2c-1), not 0. - Address 0x77 instead of 0x76: check the marking on the module or test both addresses with
i2cdetect. - Powering an unregulated module with 5 V: most BME280 modules accept 3.3-5 V, but the I2C logic level must remain at 3.3 V.
- SDA/SCL swapped: no response; swap the two wires and run i2cdetect again.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython