[英]How to retrieve USB-to-serial address?
Pyserial: A USB serial device has different addresses depending on whether I install it to a desktop (Catalina) or laptop (High Sierra): Pyserial:USB 串行设备具有不同的地址,具体取决于我将其安装到台式机(Catalina)还是笔记本电脑(High Sierra):
ser = serial.Serial('/dev/cu.usbserial', 9600) #OSX High-Sierra
ser = serial.Serial('/dev/cu.usbserial-1D120', 9600) #OSX Catalina
Is there a method to use a wildcard?有没有使用通配符的方法?
/dev/su.usbseria*
. /dev/su.usbseria*
。 The goal is one line of code that will handle either case.目标是处理任何一种情况的一行代码。
Any insight as to why -1D120
was appended, is appreciated.任何关于为什么附加
-1D120
的见解都值得赞赏。
Example例子
import serial.tools.list_ports
#Find USB Port
def find_port(): #Finds which port the arduino is plugged into
ports = list(serial.tools.list_ports.comports())
for p in ports:
if '0403' in p[2]: #unique to Osepp Uno (arduino clone)
return p[0]
Assume that the target string (regular expression) is of the format:假设目标字符串(正则表达式)的格式为:
/dev/cu.usbserial**************
/dev/cu.usbserial**************
How would the above snippet of code be modified to trap and return the USB serial device?如何修改上述代码片段以捕获并返回 USB 串行设备?
Note: This answer was cut from the question and properly posted here.注意:此答案已从问题中删除并在此处正确发布。
Retrieve USB-to-serial address and open port检索 USB 转串口地址并打开端口
YMMV : mind the algorithm limitations. YMMV :注意算法限制。 Especially the trapping string: if there is more than one instance found (trapped), the last trapped list item will be returned => it may or may not be the intended target string.
尤其是捕获字符串:如果发现(捕获)多个实例,将返回最后一个捕获的列表项=> 它可能是也可能不是预期的目标字符串。
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
#print(p[0]) #p[0] => target string
if 'usbserial' in p[0]: #OSX: Trap usbserial device /dev/cu.usbserial-1D120
serAddr=p[0]
if 'ttyUSB' in p[0]: #Ubuntu :Trap usbserial device /dev/ttyUSB0
serAddr=p[0]
ser = serial.Serial(serAddr, 9600) # Open port at 9600 baud
A third untested trap for checking windows COM ports can be added:可以添加第三个未经测试的陷阱,用于检查 windows COM 端口:
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
for p in ports:
#print(p[0]) #p[0] => target string
if 'usbserial' in p[0]: #OSX: Trap usbserial device /dev/cu.usbserial-1D120
serAddr=p[0]
if 'ttyUSB' in p[0]: #Ubuntu :Trap usbserial device /dev/ttyUSB0
serAddr=p[0]
if 'COM' in p[0]: #Windows :Trap usbserial device COM3 COM7 etc.
serAddr=p[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.