modbus_MediaPipe/CANopen.py

36 lines
1.0 KiB
Python
Raw 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.

import can
import time
# === 修改成你的介面 ===
# 如果你用 socketCAN-tcp (slcand) 綁到 can0
# bus = can.interface.Bus(bustype="socketcan", channel="can0", bitrate=500000)
# 如果是 PCAN (Peak)
# bus = can.interface.Bus(bustype="pcan", channel="PCAN_USBBUS1", bitrate=500000)
# 如果是 Kvaser
# bus = can.interface.Bus(bustype="kvaser", channel=0, bitrate=500000)
# 這裡先假設你用 socketcan
bus = can.interface.Bus(bustype="socketcan", channel="can0", bitrate=500000)
# === 設定參數 ===
node_id = 1
cob_id = 0x200 + node_id # PLC 的 RxPDO1
value = 1234 # 要送的整數值 (INT16)
# 轉成小端 (因為 PLC 是 little endian)
data_bytes = value.to_bytes(2, byteorder="little", signed=True)
# 塞進 CAN 幀
msg = can.Message(arbitration_id=cob_id, data=data_bytes, is_extended_id=False)
# 傳送多次測試
for i in range(10):
try:
bus.send(msg)
print(f"Sent {value} to PLC (COB-ID=0x{cob_id:X})")
except can.CanError:
print("Message NOT sent")
time.sleep(1)