🛠 Capteur I2C : température et pression avec BME280
Objectives
Enable the I2C bus on the Raspberry Pi 3 A+, detect a BME280 sensor (temperature/humidity/pressure), and read it using Python. The 40-pin connector exposes I2C0: SDA = GPIO2 (pin 3), SCL = GPIO3 (pin 5), 3.3 V power supply — 3.3 V logic only, no onboard ADC.
Hardware
- Raspberry Pi 3 A+ running Raspberry Pi OS Bookworm
- BME280 module (I2C, address 0x76 or 0x77 depending on the ADDR pin configuration)
- 4 Dupont wires: SDA→pin 3, SCL→pin 5, VCC→3.3 V (pin 17), GND→pin 25
- >
Complete Code
# 1) Activer I2C : sudo raspi-config -> Interface Interfacing Options -> I2C
# ou sans menu :
sudo sed -i 's/^#*dtparam=i2c_arm=on/dtparam=i2c_arm=on/' /boot/firmware/config.txt
sudo apt install -y i2c-tools python3-smbus
sudo reboot
i2cdetect -y 1 # le capteur doit répondre (0x76 ou 0x77)
#!/usr/bin/env python3
# lire_bme280.py — lecture brute des registres (adresse 0x76)
import smbus, time
BUS, ADDR = smbus.SMBus(1), 0x76
def read_regs(reg, n):
return BUS.read_i2c_block_data(ADDR, reg, n)
# configuration capteur (oversampling x2, mode forcé)
BUS.write_byte_data(ADDR, 0xF2, 0x01) # ctrl_hum
BUS.write_byte_data(ADDR, 0xF4, 0x27) # ctrl_meas
BUS.write_byte_data(ADDR, 0xF8, 0x00) # config
while BUS.read_byte_data(ADDR, 0xF3) & 0x08: # busying ?
time.sleep(0.01)
t = read_regs(0xFA, 3)
temp = ((t[0] << 16 | t[1] << 8 | t[2]) >> 4) / 100.0
print(f"Temperature : {temp:.2f} C")
Expected Verification
i2cdetect -y 1 displays an address (0x76 or 0x77) in the grid; the script displays a temperature consistent with the room (20–30 °C). In a thermal chamber, the value follows the setpoint.
Common Errors
- I2C not enabled:
i2cdetect -llists nothing → enabledtparam=i2c_arm=onand reboot. - Sensor at 0x77 while the script assumes 0x76: check the module's ADDR pin.
- SDA/SCL swapped:
i2cdetectfinds nothing and the bus remains stuck. - Stay at 3.3 V on both the power supply and logic sides on the 3 A+.
Other tutorials for this board
- Allumer une LED en C avec libgpiod sur le GPIO 40 broches
- Bouton poussoir et retour console avec gpiozero
- Premier script Python : inventaire du système
- Variation d'intensité d'une LED avec le PWM matériel
- Connexion WiFi station et administration en SSH
- Démarrage SD/USB et récupération d'une carte qui ne boot plus
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython