LoginSignup
9
5

More than 3 years have passed since last update.

[Python]ArduinoのCOMポートが変わってもコードを編集せずにポートを開く方法

Posted at

TL;DL Pyseriallist_portsdescriptionを使えばデバイス名でArduinoがどのポートに接続されているかわかる

イントロダクション

Pyserialを使用したシリアル通信を行う場合、COMポートオープンするには以下のようなコードになると思います。

import serial

arduino_ser = serial.Serial('COM5')

この方法だとArduinoのCOMポートが変わってしまった時にエラーが出てしまいます。

また、接続されているCOMポートのリストを取得し、接続する方法もありますが、Arduino以外のCOMポートを利用する機器が接続されている状況では正しく動作しません

import serial
from serial.tools import list_ports

ports=list_ports.comports()
for port in list_ports.comport():
    arduino_ser=serial.Serial(list_ports.device)

私の使用状況では、Arduinoの他にCOMポートを利用する機器が接続されている状況のため、上記コードを利用する事が出来ませんでした。

この記事ではCOMポートが変わった場合でもデバイス名からArduinoのポートを特定し、コードを編集せずにArduinoのポートを開くことが可能なコードを紹介します。

環境

  • Windows10 64bit
  • Python 3.6.3
  • Pyserial 3.4
  • Arduino Uno Rev3

方法

import serial
from serial.tools import list_ports

ports=list_ports.comports()
device=[info for info in ports if "Arduino" in info.description] #.descriptionでデバイスの名前を取得出来る
if not len(device) == 0:
   arduino_ser=serial.Serial(device[0].device)
else:
    print('Ardunoは接続されていません')

注意点

  • デバイス名にArdunoが入っているデバイスが複数個接続されている場合は、一つのArduinoのポートしか開けません

別の方法

StackOverflowでwin32comを利用した方法も見つけたため紹介いたします。

import win32com.client

wmi = win32com.client.GetObject("winmgmts:")
for ser in wmi.InstancesOf("Win32_SerialPort"):
    if "Arduino" in ser.name:
            arduino_ser = serial.Serial(ser.DeviceID)

参考リンク

StackOverflow : python : How to detect device name/id on a serial COM

Gist : pyserialでシリアルポート一覧を表示し選択させて,読み込むプログラム

9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5