Search code examples
c#detectionports

How to find which serial port is currently used?


I ve connected my mobile phone to my PC and used this,

string[] lPorts = System.IO.Ports.SerialPort.GetPortNames();

and the result was an array of port names

"COM4"
"COM3"
"COM1"
"COM7"
"COM6"

Now,How to find which serial port is currently used/to which port my mobile phone is connected in c#?


Solution

  • Obviously you will need to know the serial protocol being used to communicate. Just send a known command to each port and check back for the expected response. Ports with no device on them will timeout/throw an IOException.

    Or you if you don't want to do this through code you can try the same using HyperTerminal or another serial terminal program.

    Try something like following: (Please note I am writing this from memory and don't guarantee this will compile/that I have the method names 100% right, but it gives the general idea).

    foreach(string portname in SerialPort.GetPortNames())
    {
        // Use your connection settings - own baud rate etc
        SerialPort sp = new SerialPort(portname,4800, Parity.Odd, 8, StopBits.One); 
        try
        {
             sp.Open();
             sp.Write("Your known command to phone");
             Thread.Sleep(500);
             string received = sp.ReadLine();
    
             if(received == "expected response")
             {
                  Console.WriteLine("Phone connected to: " + portname);
                  break;
             }
        }
        catch(Exception)
        {
             Console.WriteLine("Phone NOT connected to: " + portname);
        }
        finally
        {
             sp.Close();
        }
    }