I'm making program to autodetect my Arduino using C# windows form application. For this I'm browsing through port names, assign them to serial port, write letter to port and wait if some port will response with another letter.
It all works fine until I run program on the computer where some COM ports are assigned to Bluetooth (Standard Serial over Bluetooth link). Looks like when I'm trying to .Write or .WriteLine to those ports it completely stops working.
If I manually delete those ports in Win through "Bluetooth --> more options" everything is ok.
So I tried to get around using stopwatch - give just some time to perform, but it is still not working:
`Stopwatch timer = new Stopwatch();
timer.Start();
textBox1.Text = "1";
while (timer.Elapsed.TotalSeconds < 2)
{
serialPort1.Write("q" + "\n"); //ping port
}
timer.Stop();`
What I'm doing wrong and how I can fix it?
Perhaps I can firstly find those ports and exclude them from ping?
I found this method, that looks for all ports:
`System.Management.ManagementObjectSearcher Searcher = new
System.Management.ManagementObjectSearcher("Select * from WIN32_SerialPort");
foreach (System.Management.ManagementObject Port in Searcher.Get())
{
foreach (System.Management.PropertyData Property in Port.Properties)
{
Console.WriteLine(Property.Name + " " + (Property.Value == null ? null :
Property.Value.ToString()));
}
}`
Determine if serial port is normal COM or SPP
but how I can get Bluetooth ports names to be excluded?
N.B. I'm biotech guy who just needed pump for my experiment. Hardware switches sucks --> arduino --> windows form --> suddenly found myself in here. No software background at all.
Many thanks to Raynoceros!
SOLUTION:
string[] ports = SerialPort.GetPortNames(); //This is all ports names
string[] btports = { }; // array for only bluetooth ports
// search for ports in ObjectSearher
System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher("SELECT * FROM Win32_SerialPort");
//check if port belongs to bluetooth
foreach (System.Management.ManagementObject port in searcher.Get())
{
string deviceId = port["PNPDeviceID"].ToString(); //get data from searcher
if (deviceId.Contains("BTHENUM")) //in string PNPDeviceID check for words BTHENUM (Bluetooth)
{
string portName = port["DeviceID"].ToString(); // and if it have BTHENUM than take its port name
List<string> list = new List<string>(btports.ToList()); // and using string to create array
list.Add(portName);
btports = list.ToArray(); // make array that will contain port names that have BTHENUM in description
}
}
string[] coms = ports.Except(btports).ToArray(); // then extract BTHENUM ports from all ports
// now coms contains only names of ports not associated with bluetooth