🛠 Lire un capteur sur le bus I2C
Objectives
Enable the I2C0 bus on the Raspberry Pi 2, scan the bus to find a sensor's address, and then read its measurements from Python. I2C requires only two wires (SDA, SCL) shared among multiple devices, each having an address — this is the basis for most commercial sensors.
Hardware
- Raspberry Pi 2 Model B running 32-bit Raspberry Pi OS
- 1 I2C sensor (for example BME280 or BMP280: temperature/pressure)
- 4 jumper cables: 3.3 V, GND, SDA (GPIO2, pin 3), SCL (GPIO3, pin 5)
- Packages: sudo apt install i2c-tools python3-smbus
Complete code
# 1. Activer I2C : sudo raspi-config -> Interface -> I2C, ou :
sudo sed -i 's/^#*dtparam=i2c_arm=.*/dtparam=i2c_arm=on/' /boot/config.txt
sudo reboot
# 2. Scanner le bus : le capteur doit apparaitre (ex. 0x76 ou 0x77)
i2cdetect -y 1
#!/usr/bin/env python3
"""lire_capteur.py — lecture brute d'un registre I2C."""
import smbus
import time
BUS = smbus.SMBus(1)
ADRESSE = 0x76 # adresse renvoyee par i2cdetect
REG_ID = 0xD0 # registre « chip id » (BMP/BME280)
chip_id = BUS.read_byte_data(ADRESSE, REG_ID)
print(f"Chip ID lu a 0x{ADRESSE:02X} : 0x{chip_id:02X}")
for _ in range(5):
t = BUS.read_byte_data(ADRESSE, 0xFA) # octet haut de temperature
print(f"Brut temperature (octet haut) : {t}")
time.sleep(1)
Expected verification
i2cdetect -y 1 displays a grid; the sensor's address appears clearly (never 0x03 or 0x70, which are reserved). The Python script displays a non-zero chip id (0x60 for BME280, 0x50/0x51 for BMP280) followed by five readings spaced one second apart. All 0x00s indicate incorrect wiring or address.
Common errors
- I2C not enabled: without
dtparam=i2c_arm=onand a reboot,/dev/i2c-1does not exist. - Wrong bus: it is bus 1 (
i2cdetect -y 1), not bus 0. - Sensor powered at 5 V on a module without a regulator: the Pi's I2C logic is 3.3 V; most breakouts accept this, others do not.
- Address 0x76 or 0x77: it depends on the ADDR strap; test both if
i2cdetectshows only one.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython