LoginSignup
1
0

More than 1 year has passed since last update.

[Python]Arduinoのシリアルポートを自動検出して取得

Last updated at Posted at 2022-06-11

DeviceNameで共有で使われているデバイス名を指定

import serial
from serial.tools import list_ports

class Settings:
    DeviceName = "USB-SERIAL"

def select_port(default_name=Settings.DeviceName):
    ser = serial.Serial()
    ser.baudrate = 9600  # ArduinoのSerial.beginで指定した値
    ser.timeout = 0.1  # タイムアウトの時間

    ports = list_ports.comports()  # ポートデータを取得

    # for info in ports:
    #     print(info.description)

    devices = [info.device for info in ports if default_name in info.description]

    if len(devices) == 0:
        # シリアル通信できるデバイスが見つからなかった場合
        print("error: device not found")
        return None
    elif len(devices) == 1:
        print("only found %s" % devices[0])
        ser.port = devices[0]
    else:
        # ポートが複数見つかった場合それらを表示し選択させる
        for i in range(len(devices)):
            print("input %3d: open %s" % (i, devices[i]))
        print("input number of target port >> ", end="")
        num = int(input())
        ser.port = devices[num]

    # 開いてみる
    try:
        ser.open()
        return ser
    except:
        print("error when opening serial")
        return None
1
0
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
1
0