mafap
mafap

Reputation: 391

Find which port Arduino is connected

I know how to list the available Serial Ports but whow can I find the right COM port everytime I connect my Arduino? COM Port should be printed like MessageBox.Show(COMport);

I want to read/write Arduino data in a Visual C# application.

[this didn't work for me]

Upvotes: 1

Views: 5009

Answers (3)

JackCColeman
JackCColeman

Reputation: 3807

To elaborate, the com ports are named: COM1, COM2, COM3, etc.

So, coding a loop that opens each COMn and if the open succeeds send a serial stream and see if you get the correct response.

Finally, in C you can sprintf(port_name, "COM%d", port_nr); to generate the port names for open.

Upvotes: -2

user2019047
user2019047

Reputation: 769

Open Device manager, expand "Ports (COM & LPT)". Plug in the Arduino USB connection, a new COM port shows up with name Arduino UNO (COMxx). This is on my machine as I have an Arduino UNO.

You can find this string using WMI (Windows Management Instrumentation). I am using the method below in a class, and has COMports as a public List

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Windows;

 public void getCOMportsValues()
    {
        try
        {
            if (COMports.Count > 0) COMports.Clear(); // COMports is a List<string>

            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_PnPEntity");

            foreach (ManagementObject queryObj in searcher.Get())
            {
                string s = queryObj["Name"] as string;
                if (s.Contains("(COM"))
                    COMports.Add(s);
            }
        }
        catch (ManagementException e)
        {
            MessageBox.Show("An error occurred while querying WMI data: " + e.Message);
        }
    }

Upvotes: 3

Pex
Pex

Reputation: 11

You can program your Arduino to send a specific pattern through serial and your C# listen to all COM ports, looking for the specific pattern.

Upvotes: 1

Related Questions