get com port number of an USB adapter

后端 未结 5 940
既然无缘
既然无缘 2021-01-16 17:23

I am trying to write a program that uses an arduino mega and a FTDI-based USB to RS485 adapter.

I want to make the program user-friendly, thus I don\'t wont the user

5条回答
  •  孤街浪徒
    2021-01-16 17:39

    This might work for you. I used this to dynamically read port number of Arduino on a system. Here

    description.Contains("uino")

    is to look for both Arduino and Genuino keyword for both varients of board.

        public string detectArduinoPort()
        {
            ManagementScope mScope = new ManagementScope();
            SelectQuery query = new SelectQuery("SELECT * FROM Win32_SerialPort");
            ManagementObjectSearcher objectList = new ManagementObjectSearcher(mScope, query);
    
            try
            {
                foreach (ManagementObject obj in objectList.Get())
                {
                    string description = obj["Description"].ToString();
                    string deviceId = obj["DeviceID"].ToString();
    
                    if (description.Contains("uino"))
                    {
                        return deviceId;
                    }
                }
            }
            catch (Exception)
            {
    
            }
            return "";
        }
    

提交回复
热议问题