i2c_temperature_sensor-9.ino
Python script using smbus2 module to query an I2C sensor connected to the BPI-5202 internal bus.
The I2C bus is accessible via the extended GPIO pins on the 20-pin connector or via an IO expansion module. On Loongnix or KylinOS, enable i2c-dev with 'sudo modprobe i2c-dev'. The script requires 'python3-smbus2'. Read temperature from an LM75 sensor at address 0x48 on bus 1 (adjust according to your module schematic). Run with sudo if needed for GPIO permissions.
i2c_temperature_sensor-9.ino
#!/usr/bin/env python3
# i2c_temp_monitor.py
# Exemple de lecture capteur I2C sur BPI-5202 (LoongArch)
# Nécessite : sudo apt install python3-smbus
import time
import struct
from smbus2 import SMBus
# Adresse I2C par défaut du capteur (ex: LM75)
I2C_BUS = 1 # Vérifier avec 'ls /dev/i2c-*' sur BPI-5202
I2C_ADDR = 0x48
try:
bus = SMBus(I2C_BUS)
print(f"Initialisation I2C bus {I2C_BUS} pour BPI-5202...")
while True:
try:
# Lecture du registre de température (LM75)
raw_data = bus.read_word_data(I2C_ADDR, 0x00)
# Conversion brute -> Celsius (format spécifique LM75)
temp_c = (raw_data << 8) & 0xFF00
temp_c = temp_c >> 8 # Simple décalage pour exemple
# Ajustement précis selon datasheet (ici approximation)
if temp_c > 128:
temp_c -= 256
print(f"Température: {temp_c:.2f} C")
except Exception as e:
print(f"Erreur I2C: {e}")
time.sleep(1)
except KeyboardInterrupt:
print("\nArrêt du programme.")
except Exception as e:
print(f"Erreur critique: {e}")
finally:
if 'bus' in locals():
bus.close()