Monday, February 16, 2015

What COM port is my device on?

Sometimes it's ok to let the user manually select the COM port where the device is located, other times you want to select the right device automatically.


The following code snippet loops thru all COM ports in search for a specific device ID. The connected port is the printed to a textbox.

ManagementObjectCollection ManObjReturn;
ManagementObjectSearcher ManObjSearch;
ManObjSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
ManObjReturn = ManObjSearch.Get();

foreach (ManagementObject ManObj in ManObjReturn)
{
    string deviID = ManObj["PNPDeviceID"].ToString().Split('\\')[1];
    if(deviID == "VID_2341&PID_0001") // Arduino uno devID
    {
        richTextBox1.AppendText("\nArduino uno is connected on  "
            + ManObj["DeviceID"].ToString());
        break;
    }
}

The devID might be a bit confusing, but we are just splitting a long string to get the relevant info. At the end of the PNPDeviceID it is also appended a counter, starting at 1 and incrementing in case you have many identical devices attached.
The code requires importing a reference to System.Management

No comments:

Post a Comment