🛠 Lire un capteur I2C (température/humidité)

Raspberry Pi 3 Model B+ (2018) — Board Sheet · intermediaire · Schéma : IMG-model-3b-plus-intermediaire-2-model3bp-i2c-capteur.svg — Capteur I2C relié à SDA (broche 3) et SCL (broche 5), 3,3 V et GND, bus avec résistances de pull-up

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

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

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials