bpi-cm5-spi-thermal-sensor-read-10.ino
Python example using the spidev library to read a digital temperature sensor (MCP9808/TMP102) via the BPI-CM5 SPI bus.
This script requires enabling the SPI interface in the OS (via armbian-config or Device Tree overlay). Install 'python3-spidev'. The code is adapted for the default SPI bus of the Amlogic A311D2. Verify the presence of /dev/spidev1.0. Ensure the sensor is correctly wired (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()