bpi-cm5-spi-thermal-sensor-read-10.ino
Exemple Python utilisant la bibliothèque spidev pour lire un capteur de température (type MCP9808 ou TMP102) sur le bus SPI de la BPI-CM5.
Ce script nécessite l'activation de l'interface SPI dans le système d'exploitation (via armbian-config ou overlay Device Tree). Installez 'python3-spidev'. Le code est adapté pour le bus SPI par défaut de l'Amlogic A311D2. Vérifiez la présence de /dev/spidev1.0. Assurez-vous que le capteur est correctement câblé (CLK, MOSI, MISO, GND).
bpi-cm5-spi-thermal-sensor-read-10.ino
import spidev
import time
import sys
# SPI Settings for BPI-CM5 Amlogic A311D2
# Usually bus 1, device 0 (check /dev/spidev1.0)
SPI_BUS = 1
SPI_DEV = 0
SPI_SPEED = 1000000 # 1 MHz
def read_temperature_mcp9808(spi):
"""
Reads temperature from MCP9808.
Address 0x30, Command 0x05 (Ambient Temperature)
"""
try:
# Send command to read ambient temperature
msg = [0x05]
spi.xfer2(msg)
# Read 2 bytes of data
resp = spi.xfer2([0x00, 0x00])
# Combine MSB and LSB
raw_temp = (resp[0] << 8) | resp[1]
# Handle sign bit (13th bit)
if raw_temp & 0x2000:
temp = -raw_temp & 0x1FFF
temp = temp / 256.0
else:
temp = (raw_temp & 0x1FFF) / 256.0
return temp
except Exception as e:
print(f"SPI Error: {e}")
return None
try:
spi = spidev.SpiDev()
spi.open(SPI_BUS, SPI_DEV)
spi.max_speed_hz = SPI_SPEED
spi.mode = 0
print(f"Reading MCP9808 Temperature on SPI{SPI_BUS}.{SPI_DEV}...")
while True:
temp = read_temperature_mcp9808(spi)
if temp is not None:
print(f"Temperature: {temp:.2f} C")
time.sleep(1)
except KeyboardInterrupt:
print("\nExiting...")
except FileNotFoundError:
print("Error: SPI device not found. Enable SPI in Armbian config (armbian-config).")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
if 'spi' in locals():
spi.close()