modbus_MediaPipe/python_modbus.py

26 lines
728 B
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.

from pymodbus.client.sync import ModbusTcpClient
import os
os.add_dll_directory(r"C:\Users\huiting\Desktop\PCAN-Basic\x64") # 換成 DLL 的實際路徑
import time
# 設定 PLC IP 和 Port
client = ModbusTcpClient('169.254.11.8', port=502)
# 嘗試連線
if client.connect():
print("已連接到 PLC")
i = 0
while True:
# 寫入值 i 到 HR 1630地址 1630Function Code 0x10
result = client.write_register(address=1630, value=i, unit=255)
print(f"寫入 {i} 到 HR 1630")
i += 1
time.sleep(1)
else:
print("❌ 無法連接到 PLC請檢查 IP 與 Slave 模式是否啟用")
# 離開後關閉連線(若非 while True 模式需加上)
# client.close()