rs485-modbus-master.py
Python script using the pyserial library to communicate over the isolated RS485 port.
Install pyserial via pip. The BPI-5202 has two isolated RS485 ports. Identify the correct device (/dev/ttySx) via dmesg. Ensure the sensor is powered by the 24V output if needed.
rs485-modbus-master.py
import serial
import time
# Configuration du port série RS485 (ex: /dev/ttyS1)
# Attention: Vérifier les paramètres de débit (baudrate) selon votre capteur
port = '/dev/ttyS1'
baudrate = 9600
parity = serial.PARITY_NONE
stopbits = serial.STOPBITS_ONE
bytesize = serial.EIGHTBITS
try:
ser = serial.Serial(
port=port,
baudrate=baudrate,
parity=parity,
stopbits=stopbits,
bytesize=bytesize,
timeout=1
)
print(f"Ouverture du port {port} réussie.")
# Exemple de trame Modbus RTU pour lire un registre (Adresse 1, Fonction 03, Registre 0, Quantité 1)
# Note: Ceci est une trame brute, l'utilisation d'une bibliothèque comme 'pymodbus' est recommandée
# pour la gestion CRC correcte. Ici, on simule l'envoi.
command = b'\x01\x03\x00\x00\x00\x01\x84\x0A'
while True:
ser.write(command)
response = ser.read(7) # Lecture d'une réponse type (7 octets)
if response:
print(f"Données reçues: {response.hex()}")
else:
print("Aucune réponse")
time.sleep(1)
except Exception as e:
print(f"Erreur: {e}")
finally:
if 'ser' in locals() and ser.is_open:
ser.close()