Finding Serial Ports in Python on the Raspberry Pi

Nothing to do with the post. But another picture I like

One of the more annoying quirks of using usb serial ports is that they move about a bit. The precise port that you get when you plug the same device into your computer is subject to change. This can be annoying; particularly if you want to make something that just works. With all that in mind I present this:

def get_port(self, portNames):
result = None
for portName in portNames:
    try:
        print("Connecting to " + portName)
        result = serial.Serial(portName, 115200)
        print("    Connected")
        return result
    except :
        print("    Connect failed to " + portName)
return result

The get_port function is given a list of ports that might have something behind them. It then works through the list trying each one and returns either a port that worked or None.

ports = ["/dev/ttyACM0","/dev/ttyACM1","/dev/ttyACM2"]
serial_port = self.get_port(ports)

You call it as shown above. The ports variable contains a list of addresses. When the function completes it will either have a useable port or None. I’ve found it quite useful.