PySerial autofind serial port

here’s a small script that I found somewhere online, and heavily modified to auto search for and connect to the first serial port it can find, skipping the built in serial port for last.

import serial
locations=[‘/dev/ttyACM0’, ‘/dev/ttyACM1′,’/dev/ttyACM2’, ‘/dev/ttyACM3′,’/dev/ttyACM4’, ‘/dev/ttyACM5′,’/dev/ttyUSB0′,’/dev/ttyUSB1′,’/dev/ttyUSB2′,’/dev/ttyUSB3’, ‘/dev/ttyUSB4’, ‘/dev/ttyUSB5’, ‘/dev/ttyUSB6’, ‘/dev/ttyUSB7’, ‘/dev/ttyUSB8’, ‘/dev/ttyUSB9’, ‘/dev/ttyUSB10′,’/dev/ttyS0’, ‘/dev/ttyS1’, ‘/dev/ttyS2’, ‘com2’, ‘com3’, ‘com4’, ‘com5’, ‘com6’, ‘com7’, ‘com8’, ‘com9’, ‘com10’, ‘com11’, ‘com12’, ‘com13’, ‘com14’, ‘com15’, ‘com16’, ‘com17’, ‘com18’, ‘com19’, ‘com20’, ‘com21’, ‘com1’, ‘end’]

for device in locations:
try:
serialport = serial.Serial(device, 2400, timeout = 0)
break
except:
if device == ‘end’:
print “Unable to find Serial Port, Please plug in cable or check cable connections.”
exit()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: