Python CAN Bus サンプルコード

UIROBOT CAN Bus 製品の Python 開発サンプルコード。python-can ライブラリ、モータ制御、データ収集。

# Python CAN Bus サンプルコード このページでは、Python を使用して UIROBOT CAN bus モーションコントローラと通信するためのサンプルコードを提供します。 --- ## Quick Selection | 接続方法 | 対応製品 | ドキュメント | |---------|---------|-------------| | **SocketCAN (Linux)** | UIM342, UIM342A | [AN014] | | **PCAN (Windows)** | UIM342, UIM342A | [AN015] | | **シリアル (UIM2513)** | UIM342, UIM342A, UIM1616 | [AN016] | ## セクション 1: SocketCAN (Linux) ### 背景 Linux 環境では SocketCAN インターフェースを使用して CAN bus デバイスと通信します。 ### サンプルコード ```python import can import time # CAN バスに接続 bus = can.Bus(interface='socketcan', channel='can0', bitrate=500000) # モータ速度設定メッセージを送信 msg = can.Message( arbitration_id=0x01, data=[0x01, 0xF4, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], is_extended_id=False ) bus.send(msg) print("メッセージ送信完了") # 応答を受信 response = bus.recv(timeout=1) if response: print(f"受信: ID={response.arbitration_id}, データ={response.data.hex()}") ``` ## セクション 2: シリアル (UIM2513) ### サンプルコード ```python import serial import time ser = serial.Serial('COM3', 57600, timeout=1) # UIMessage フレームを送信(AA + ID + CW + データ + CRC + CC) msg = bytes([0xAA, 0x05, 0x1D, 0xE8, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD3, 0x7D, 0xCC]) ser.write(msg) time.sleep(0.1) response = ser.read(16) print(f"応答: {response.hex()}") ser.close() ``` --- ## ダウンロード | アプリケーションノート | 説明 | ダウンロードリンク | |---------------------|------|-----------------| | AN014 | Python SocketCAN + UIM342 | [Download ZIP](https://www.uirobot.com) | | AN015 | Python PCAN + UIM342 | [Download ZIP](https://www.uirobot.com) | | AN016 | Python UIM2513 + UIM342 | [Download ZIP](https://www.uirobot.com) | --- ## 関連ドキュメント - [Arduino CAN Bus サンプルコード](/docs/arduino-examples) - [C++ Windows サンプルコード](/docs/cpp-windows-examples) - [Raspberry Pi CAN Bus サンプルコード](/docs/raspberry-pi-examples) --- *最終更新: 2026-07-03*