| 15 | |
| 16 | |
| 17 | def ListAvailablePorts(): |
| 18 | # This function return a list containing the string names for Virtual Serial Ports |
| 19 | # availables in the computer (this function works only for Windows & Linux Platforms but you can extend it) |
| 20 | # if there isn't available ports, returns an empty List |
| 21 | AvailablePorts = [] |
| 22 | platform = sys.platform |
| 23 | if platform == "win32": |
| 24 | for i in range(255): |
| 25 | try: |
| 26 | ser = serial.Serial(i, 9600) |
| 27 | except serial.serialutil.SerialException: |
| 28 | pass |
| 29 | else: |
| 30 | AvailablePorts.append(ser.portstr) |
| 31 | ser.close() |
| 32 | |
| 33 | elif platform == "linux": |
| 34 | for i in range(0, 255): |
| 35 | try: |
| 36 | ser = serial.Serial("/dev/ttyUSB" + str(i)) |
| 37 | except serial.serialutil.SerialException: |
| 38 | pass |
| 39 | else: |
| 40 | AvailablePorts.append("/dev/ttyUSB" + str(i)) |
| 41 | ser.close() |
| 42 | else: |
| 43 | print( |
| 44 | """This method was developed only for linux and windows |
| 45 | the current platform isn't recognised""" |
| 46 | ) |
| 47 | if len(AvailablePorts) == 0: |
| 48 | print("NO port in use") |
| 49 | return 0 |
| 50 | else: |
| 51 | return AvailablePorts |
| 52 | |
| 53 | |
| 54 | # EXAMPLE OF HOW IT WORKS |