🛠 Lire un capteur sur le bus I2C
Objectives
Enable the I2C bus of the BCM2835, detect a sensor (example: BME280 temperature/pressure/humidity) on I2C0 of the P1 connector, and read a measurement from Python using smbus.
Hardware
- Raspberry Pi Model B Rev 2, Raspbian legacy 32-bit
- I2C sensor 3.3 V (BME280 or equivalent), pull-up resistors if the module does not have them
- SDA on GPIO0 (P1-3), SCL on GPIO1 (P1-5), 3.3 V and GND. I2C0 is indeed on GPIO0/1 on this board; no reliable default address without
i2cdetect. sudo apt install i2c-tools python-smbus
Complete code
# 1) Activer I2C: dans /boot/config.txt ajouter la ligne puis redemarrer
sudo nano /boot/config.txt
# dtparam=i2c_arm=on
sudo reboot
# 2) Scanner le bus (adresse attendue: 76 ou 77 pour un BME280)
sudo i2cdetect -y 1
#!/usr/bin/env python
# lire_temp.py - lecture brute d'un registre via smbus
import smbus
bus = smbus.SMBus(1) # i2c-1 (le seul expose sur P1)
ADDR = 0x76 # adresse trouvee a l'etape i2cdetect
try:
who = bus.read_byte_data(ADDR, 0xD0)
print("chip id: 0x%02x" % who) # 0x60 pour un BME280
except IOError:
print("Pas de reponse sur l'adresse %02x" % ADDR)
Expected verification
i2cdetect -y 1 displays the sensor address in the grid; the Python script prints the chip ID (0x60 for a BME280). No XX should remain everywhere in the grid.
Common errors
dtparam=i2c_arm=onforgotten or reboot omitted:i2cdetectresponds "Could not open file /dev/i2c-1".- SDA/SCL swapped: nothing appears in the scan, the sensor does not "respond".
- 5 V sensor powered at 3.3 V (or vice versa on the lines): check the logic level, the board is 3.3 V.
- Wrong address (0x76 vs 0x77 depending on the SDO pin): scan before coding.
Other tutorials for this board
Code examples for this board
led_blink.pyPythonbutton_led.pyPythonservo_sweep.pyPythondht_temp.pyPythonoled_i2c.pyPythonmcp3008_read.pyPython