Software_and_hardware/Версия_2.0/Server.py

54 lines
1.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#python d:\Антоше\Универ\Гит\Software_and_hardware\Версия_2.0\Server.py
import serial
import serial.tools.list_ports
import minimalmodbus
import time
def find_arduino_port():
ports = list(serial.tools.list_ports.comports())
for port in ports:
if "Arduino" in port.description or "CH340" in port.description:
return port.device
return None
# Настройки порта
port = find_arduino_port() # Укажите порт, к которому подключен Arduino
slave_id = 1 # ID устройства (адрес Arduino)
baudrate = 9600
timeout = 1 # Время ожидания в секундах
# Настроим модбас клиента
client = minimalmodbus.Instrument(port, slave_id) # Создаем объект клиента Modbus
client.serial.baudrate = baudrate # Устанавливаем скорость
client.serial.timeout = timeout # Время ожидания ответа
client.mode = minimalmodbus.MODE_RTU # Используем RTU
# Ожидаем получения данных от Arduino
try:
while True:
try:
# Чтение 4 регистров с адреса 0
result = client.read_registers(0, 1, functioncode=3)
print(f"Полученные данные: {result}")
break # Выход из цикла, если данные получены
except minimalmodbus.NoResponseError:
print("Ошибка: Нет ответа от устройства. Повторяем...")
time.sleep(1) # Подождать 1 секунду и попробовать снова
except Exception as e:
print(f"Ошибка: {e}")
break
except KeyboardInterrupt:
print("Программа остановлена пользователем")