🛠 Lire un capteur sur le bus I2C

Raspberry Pi Model B Revision 2 (2012) — Board Sheet · intermediaire · Schéma : IMG-model-b-rev2-intermediaire-2-modelb2-i2c-capteur.svg — Bus I2C du Model B Rev 2 : SDA (GPIO0, P1-3) et SCL (GPIO1, P1-5) reliés à un capteur BME280 avec résistances de pull-up

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials