在 C# 中检测 Arduino 端口 [英] Detect Arduino port in C#
问题描述
我试图打开每个端口并串行发送
,我的微控制器将响应
之后 C# 代码必须退出 for 每个循环.
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.
我在 serialPort.PortName = str;
行遇到问题.两次迭代后,不再继续.
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.
我知道 C++ 中的 OOP.但我是 C# 的新手.我不确定为什么循环失败.
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);
}
}
}
}
推荐答案
我没有多个串口,但是当我编译和执行你的代码时,我注意到如果在执行过程中出错,你并没有关闭串口读.我建议你修改你的代码如下:
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.
这篇关于在 C# 中检测 Arduino 端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!