我有Arduino Nano控制一台连接到我的电脑并通过C#控制的直流电机。 唯一的问题是它现在可以在我的计算机上工作,如果我将它连接到另一台PC,它将无法工作,除非它使用相同的串行端口。这就是我希望COM端口“自行设置”的原因。有可能吗?如果没有,我想制作另一个表格只是为了输入COM端口的数量,但我想尽可能避免这种情况。先感谢您。 这是我的代码:
public partial class Form1 : Form
{
String s = "0";
string brojPorta = "COM5";
int vrijednost = 0;
System.IO.Ports.SerialPort serialPort1;
public Form1()
{
InitializeComponent();
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components);
serialPort1.PortName = brojPorta;
serialPort1.BaudRate = 9600;
serialPort1.Open();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (serialPort1.IsOpen) serialPort1.Close();
}
private void Klizac1_Scroll(object sender, ScrollEventArgs e)
{
vrijednost = Klizac1.Value;
s = (vrijednost * 10.24).ToString();
serialPort1.Write(s + '\n');
label1.Text = ((vrijednost-50)*2).ToString()+"%";
}
private void btn_Zaustavi_Click(object sender, EventArgs e)
{
Klizac1.Value = 50;
label1.Text = "0";
s = (Klizac1.Value * 10.24).ToString();
serialPort1.Write(s + '\n');
}
}
答案 0 :(得分:1)
首先,您必须枚举所有端口。请参阅此问题:How to find available COM ports?
然后你必须尝试在每个端口上连接超时,直到找到它为止。
更谨慎的方案是枚举下拉列表中的可用端口,并让用户选择它所连接的端口。
答案 1 :(得分:0)
这里可能存在一些陷阱,但这个例子似乎有效:
/*Use the WMI to search for the Arduino device on a serial port driver
and assign the serial port to the device*/
ManagementObjectSearcher SerialPortSearcher =
new ManagementObjectSearcher(
"root\\CIMV2",
"SELECT * FROM Win32_SerialPort");
foreach (ManagementObject SerialPortObject in SerialPortSearcher.Get())
{
if (SerialPortObject["Description"].ToString() == "Arduino Mega 2560")
{
SerialPort _serialPort =
new SerialPort(SerialPortObject["DeviceID"].ToString());
break;
}
}