Xpleria
Xpleria

Reputation: 5873

Detect Arduino port in C#

I'm trying to open each port and send <mccon> serially, for which my microcontroller will respond <connected>\n after which the C# code must exit the for each loop.

I'm having a problem at the serialPort.PortName = str; line. After two iterations, it does not continue further.

I tried doing this manually too. I made a drop down and selected ports one by one. After the second port, it does not allow to change the serial Port. But in case I select within two tries, it works fine.

I know OOP in C++. But I'm new to C#. I'm not sure why the loop fails.

public Form1()
{
    InitializeComponent();
    send_button.Enabled = false;

    //Availabe COM ports
    SerialPort tmp;
    foreach(string str in SerialPort.GetPortNames())
    {
        tmp = new SerialPort(str);
        if (tmp.IsOpen == false)
        {
            serialPort.PortName = str;

            try
            {
                //Open serial port
                serialPort.Open();
                serialPort.BaudRate = 9600;
                serialPort.WriteTimeout = 10;
                serialPort.ReadTimeout = 10;
                serialPort.Write("<mccon>");
                readtxt.Text = serialPort.ReadTo("\n");
                if (readtxt.Text == "<connected>")
                {
                    send_button.Enabled = true;
                    port_combobox.Enabled = false;
                    break;
                }
                else
                {
                    serialPort.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

Upvotes: 2

Views: 4613

Answers (2)

Random IT Guy
Random IT Guy

Reputation: 623

Could you execute this code and return what it shows? It might show some information about the Arduino port which you can then use for the serialport.

Add a reference to System.Management and also add the using, and then try the code:

using System.Management;

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

    foreach (ManagementObject queryObj in searcher.Get())
    {
        if (queryObj["Caption"].ToString().ToUpper().Contains("ARDUINO"))
        {
            Console.WriteLine(queryObj["Caption"]);
            foreach (PropertyData pd in queryObj.Properties) { Console.WriteLine(pd.Name + " : " + pd.Value); }
        }
    }
}
catch (ManagementException e)
{
    Console.WriteLine(e.Message);
}
Console.ReadKey();

Upvotes: 0

David Hope
David Hope

Reputation: 2256

I don't have multiple serial ports, but when I compiled and executed your code, I noticed that you are not closing the serial port if it errors during the read. I suggest you modify your code as follows:

        SerialPort tmp;
        foreach (string str in SerialPort.GetPortNames())
        {
            tmp = new SerialPort(str);
            if (tmp.IsOpen == false)
            {

                serialPort.PortName = str;

                try
                {
                    //open serial port
                    serialPort.Open();
                    serialPort.BaudRate = 9600;
                    serialPort.WriteTimeout = 10;
                    serialPort.ReadTimeout = 10;
                    serialPort.Write("<mccon>");
                    String s = serialPort.ReadTo("\n");
                    if (s == "<connected>")
                    {
                        break;
                    }
                    else
                    {
                        serialPort.Close();
                    }
                }
                catch (TimeoutException)
                {
                    serialPort.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

I'm not sure the effect on changing the port name while it's open, but it could well cause the issues you are seeing.

Upvotes: 2

Related Questions