我有Arduino Nano控制直流電機連接到我的電腦,並通過C#控制。 唯一的問題是,它現在在我的計算機上工作,如果我將它連接到另一臺PC,它將不會工作,除非它使用相同的串行端口。這就是爲什麼我想讓COM端口「自行設置」的原因。有可能嗎?如果沒有,我想製作另一個表單來輸入COM端口的數量,但如果可能,我想避免這種情況。先謝謝你。 這是我的代碼:在C#中自動調整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');
}
}
通過COM口談論到Arduino的能力是僅用於調試和開發。它不打算便攜。但是你可以'搜索'可用的COM端口,並根據它的外觀選擇一個。如果你真的需要爲你的Arduino創建一個服務器,你將需要添加一個用戶選擇功能,因爲自動綁定並不總是工作。以ArduCopter項目的Mission Planner爲例。它試圖自動綁定,但它幾乎從來沒有工作。 – Jasmine
如果您正在編寫的Nana代碼包含查詢命令,該命令返回一些標識符。完成後,打開每個端口,發送查詢並檢查響應。編程其他微控制器時,我使用了這種技術。缺點是未連接的COM端口需要一段時間才能超時。 – dbasnett