Pyserial: A USB serial device has different addresses depending on whether I install it to a desktop (Catalina) or laptop (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*
. The goal is one line of code that will handle either case.
Any insight as to why -1D120
was appended, is appreciated.
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**************
How would the above snippet of code be modified to trap and return the USB serial device?
Note: This answer was cut from the question and properly posted here.
Retrieve USB-to-serial address and open port
YMMV : mind the algorithm limitations. 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:
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.