🛠 Lire un capteur I2C (température/humidité)
Objectives
Enable the I2C bus on the 40-pin connector, detect a connected sensor (for example BME280 or BMP280, address 0x76 or 0x77), read temperature and humidity in Python, and understand the role of pull-up resistors and the 7-bit address. The I2C bus on the connector uses SDA (pin 3) and SCL (pin 5), with 3.3 V logic.
Hardware
- Raspberry Pi 3 Model B+ type board running Raspberry Pi OS
- 1 I2C sensor (BME280/BMP280/SHT31 — adjust the address accordingly)
- 4 Dupont wires: 3.3 V (pin 1), GND (pin 6), SDA (pin 3), SCL (pin 5)
sudo apt install -y i2c-tools python3-smbus
Complete Code
# 1. Activer I2C : sudo raspi-config -> Interface Options -> I2C (ou config.txt)
echo 'dtparam=i2c_arm=on' | sudo tee -a /boot/firmware/config.txt
sudo reboot
# 2. Scanner le bus : le capteur doit répondre, p. ex. 0x76
sudo i2cdetect -y 1
#!/usr/bin/env python3
"""Lecture BMP280 en brut via smbus (adresse 0x76)."""
import smbus, time
BUS = smbus.SMBus(1)
ADDR = 0x76 # 0x77 si la broche SDO est au 3.3 V — voir i2cdetect
# Séquence simplifiée d'initialisation BMP280 (regs de configuration)
BUS.write_byte_data(ADDR, 0xF4, 0x27) # oversampling x16/x1, mode forcé
BUS.write_byte_data(ADDR, 0xF5, 0x00) # config, filtre off
time.sleep(0.05)
def lire_registre2(reg):
hi, lo = BUS.read_i2c_block_data(ADDR, reg, 3)[1:3]
return (hi << 8) | lo
while True:
adc_t = lire_registre2(0xFA) # température brute (MSB, LSB, XLSB)
t_c = (adc_t / 16.0) / 100.0 # conversion indicative, non calibrée
print(f"Temperature brute: {adc_t} (~{t_c:.1f} C) Ctrl-C pour sortir")
time.sleep(2)
Expected Verification
i2cdetect -y 1 displays a grid with the sensor's address (typically 0x76/0x77). The script displays a value that changes when you warm the sensor with your finger. If you see -- -- everywhere: SDA/SCL wiring is reversed or I2C is not enabled.
Common Errors
- I2C not enabled:
/dev/i2c-1is missing,i2cdetectcomplains — enable the overlay and reboot. - SDA/SCL reversed: nothing responds to the scan; swap the two wires.
- Powering a 3.3 V sensor with 5 V without a regulator: risk of destruction; the I2C bus is 3.3 V.
- Wrong address: SDO connected to GND gives 0x76, connected to 3.3 V gives 0x77 — check
i2cdetectrather than guessing. - Bus without pull-ups: breakout modules include them; for a bare sensor, add 4.7 kΩ resistors to 3.3 V on SDA and SCL.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython