i2c-temp-sensor-python.py

Banana Pi BPI-RT2: AX3000 WiFi 6 Router Board · File : i2c-temp-sensor-python.py · Language : Python · Use case : Lire la température d'un capteur I2C (ex: LM75) connecté à l'en-tête d'extension.

Python script using the smbus library to query an I2C temperature sensor.

Install dependencies with 'opkg install python3 python3-smbus python3-pip' then 'pip3 install smbus2' if needed. The script assumes I2C bus 0 is enabled in the device tree. Connect the sensor to the SDA/SCL pins of the 5 or 9-pin header. Verify the I2C address with 'i2cdetect -y 0' before running.

i2c-temp-sensor-python.py

import smbus
import time

# Adresse I2C typique pour LM75 (vérifier datasheet)
I2C_BUS = 0
I2C_ADDR = 0x48

def read_temperature():
    try:
        bus = smbus.SMBus(I2C_BUS)
        # Lecture du registre de température (MSB puis LSB)
        msb = bus.read_byte_data(I2C_ADDR, 0x00)
        lsb = bus.read_byte_data(I2C_ADDR, 0x01)
        
        # Conversion 11-bit signed value
        temp = (msb << 8) | lsb
        if temp > 0x7FF:
            temp -= 0x1000
        temp_c = temp / 256.0
        return temp_c
    except Exception as e:
        print(f"Erreur I2C: {e}")
        return None

if __name__ == "__main__":
    print("Lecture température (Ctrl+C pour arrêter)")
    while True:
        t = read_temperature()
        if t is not None:
            print(f"Température: {t:.2f} °C")
        time.sleep(2)

← Back to the board