0

I am making app in python, that connects with Arduino. I want this app to work on different computers, when arduino is connected to any port. I was trying to do a function that checks to which port is arduino connected to:

def arduinoConnect():
    t=0
    temp = 0;
    while 1:
        i = str(t)
        try:
           temp = serial.Serial('com'+i, 9600)
           if temp:
               print("COM" + i + " Connected")
               break
        except:
            print("COM" + i + " Empty")
        t = t + 1

        if t == 41:
            break
    return temp

But this code only sees if anything is connected, so when i am also using some bluetooth devices, or other microcontrolers, it takes the device that is connected to the com port with the lowest number. Next idea was to take PID and VID number:

import serial
import serial.tools.list_ports

for port in serial.tools.list_ports.comports():
    print(port.hwid)

But i have one more device connected to COM Port, that gives exactly the same numbers, only different location: USB VID:PID=1A86:7523 SER= LOCATION=1-4 USB VID:PID=1A86:7523 SER= LOCATION=1-5

I also tried to get a specific id of a connected USB device:

import serial

def serial_ports():
    ports = ['COM%s' % (i + 1) for i in range(256)]

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
            print(s)
        except (OSError, serial.SerialException):
            pass
    return result


if __name__ == '__main__':
    print(serial_ports())

And it returns the ID of a device, which is unique to every device, but changes every time i disconnect and connect again the device. My question is how to let my code recognize and connect one and only device I want? On any computer, connected to any port.

thehusk
  • 3
  • 4

1 Answers1

0

I understand your problem as such that you wish to have python code that can connect to an arduino device which is connected to any port, on any computer.

So the solution is to uniquely identify the arduino device even when other devices are plugged in. It should work when you get the device serial number:

import serial
import serial.tools.list_ports

def get_arduino_serial_number():
    for port in serial.tools.list_ports.comports():
        if 'Arduino' in port.description:
            return port.serial_number
    return None

whether this works or not is dependent on port.description.

Change USB COM port description
Get ports by description

With the serial number of the Arduino device, you can then connect to it using:

ser = serial.Serial(port='COMx', baudrate=9600, timeout=1,
                                parity=serial.PARITY_NONE,
                                stopbits=serial.STOPBITS_ONE,
                                bytesize=serial.EIGHTBITS)

Opening serial ports | pySerial

SirLoort
  • 1
  • 1