Movatterモバイル変換


[0]ホーム

URL:


LoginSignup
29

Go to list of users who liked

24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでArduinoが刺さってるポートを自動取得

Posted at

PythonからArduinoにシリアルで文字列を送る場合、pyserialを使って、こんな感じで書くと思います。

importserialser=serial.Serial()ser.baudrate=9600ser.port=2# COM3->2,COM5->4ser.open()ser.write("Hello")

ser.portはUSBを抜き差しするたびに変わるので、Arduino IDEでポートを確認し、Macの場合はser.port = "/dev/tty.usbmodem1451"、WindowsだとCOM3に刺さってる場合、ser.port = 2と書くわけですが、抜き差しするたびに変わって面倒ということで、こういう書き方も用意されてます。

importserialimportserial.tools.list_portsser=serial.Serial()ser.baudrate=9600ser.port=list(serial.tools.list_ports.comports())[0][0]ser.open()ser.write("Hello")

この書き方、環境によっては失敗するみたいで、Macなら/dev配下を適当に探せば見つかるだろうと、こういう書き方を試してみたら、ちゃんと動きました。

ser=serial.Serial()ser.baudrate=9600forfileinos.listdir('/dev'):if"tty.usbmodem"infile:ser.port='/dev/'+fileser.open()

Windowsの場合、数字で指定されるので、こんな書き方でもいいですね。

ser=serial.Serial()ser.baudrate=9600foriinrange(100):try:ser.port=iser.open()breakexcept:i=i
29

Go to list of users who liked

24
2

Go to list of comments

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
29

Go to list of users who liked

24

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?


[8]ページ先頭

©2009-2025 Movatter.jp