🛠 Lire un capteur sur le bus I2C

Raspberry Pi 2 Model B (2015) — Board Sheet · intermediaire · Schéma : IMG-model-2b-intermediaire-2-model2b-i2c-capteur.svg — bus I2C0 du connecteur J8 (SDA/SCL) relié à un capteur de température avec adresses 0x76/0x77 détectées par i2cdetect

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials