Search code examples
pythonbashtty

Detect which /dev/ttyACM is open


Is their a command that returns what /dev/ttyACM* is open. At some stage in the script it disconnects the usb and reconnects but the ACM increments after this so the variable port = /dev/ttyACM0 now is /dev/ttyACM1. I want to detect which /dev/ttyACM* is open. So port = return (command to find ACM)


Solution

  • Using glob and serial, this should do the trick:

    import glob
    import serial
    
    def find_ports():
        ports = glob.glob('/dev/ttyACM[0-9]*')
    
        res = []
        for port in ports:
            try:
                s = serial.Serial(port)
                s.close()
                res.append(port)
            except:
                pass
        return res