I Love Stackoverflow
I Love Stackoverflow

Reputation: 6868

How to know on which serial port external device is connected and read data from that device?

I have attached 1 device which generated some random number and i want to read that number through my Windows application.

I am using this code:

public static void Main()
{
    SerialPort mySerialPort = new SerialPort("COM19");

    mySerialPort.BaudRate = 115200;
    mySerialPort.Parity = Parity.None;
    mySerialPort.StopBits = StopBits.One;
    mySerialPort.DataBits = 8;
    mySerialPort.Handshake = Handshake.None;

    mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

    mySerialPort.Open();

    Console.WriteLine("Press any key to continue...");
    Console.WriteLine();
    Console.ReadKey();
    mySerialPort.Close();
}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort sp = (SerialPort)sender;
    string indata = sp.ReadExisting();
    Debug.Print("Data Received:");
    Debug.Print(indata);
}

With this code I am successfully getting data.

But problem here is I have hardcoded my com port(Com19) that is from device manager I have checked that to which port my device is connected so I have hardcoded that but I don't want to do this.

Instead I will give user 1 dropdown in which user will see only that port to which user device is connected. So when fetching data from this connected device I will use that user selected dropdown port.

I am very much new to windows application and never done anything related to serial port.

Upvotes: 0

Views: 1329

Answers (2)

Alexej Sommer
Alexej Sommer

Reputation: 2679

When I have arduino connected to com port. I have use this code (assuming that arduino returned text with "Info from Arduino" inside):

SerialPort currentPort; // global variables
bool ArduinoPortFound = false;

...

        try
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                currentPort = new SerialPort(port, 9600);
                if (ArduinoDetected())
                {
                    ArduinoPortFound = true;
                    break;
                }
                else
                {
                    ArduinoPortFound = false;
                }
            }
        }
        catch { }

......

        private bool ArduinoDetected()
    {
        try
        {
            currentPort.Open();
            System.Threading.Thread.Sleep(1000); 

            string returnMessage = currentPort.ReadLine();
            currentPort.Close();

            if (returnMessage.Contains("Info from Arduino"))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
    }

UPDATE: Or you can also use Windows Management Instrumentation (WMI)

Here is article about it: How to programmatically find a COM port by friendly name

Upvotes: 2

ViKu
ViKu

Reputation: 235

ManagementObjectCollection mReturn;
ManagementObjectSearcher mSearch;
mSearch = new ManagementObjectSearcher("Select * from Win32_SerialPort");
mReturn = mSearch.Get();

Combobox cboPort = new Combobox();

foreach (ManagementObject mObj in mReturn)
{
   cboPort.Items.Add(mObj["Name"].ToString());
}

Modify your code as follows

SerialPort mySerialPort = new SerialPort(cboPort.Text);

I hope this will help you, and do modification according to your requirement.

Upvotes: 1

Related Questions