[英]Interfacing Arduino with pc GUI using C#
我只是C#的初學者。 我現在正在嘗試將arduino與GUI應用程序接口。 我需要一個小的功能來自動檢測我連接了Arduino的端口。 我嘗試使用嵌套的“ try and catch”塊,但失敗了。 誰能建議一種自動選擇arduino所連接的端口並打開該端口的好方法,以便我們可以直接對在該arduino中執行不同功能的其他交換機進行編碼。
最近,我遇到了同樣的情況,我編寫了此方法來檢查我們的設備,所有需要設置您的設備以在特定輸入上發送特定模式。 在此示例中,如果您發送0x33,則您的設備必須發送0x8A來標識自己。
public enum SerialSignal
{
SendSync = 0x33,
ReceiveSync = 0x8A,
}
private static SerialPort _arduinoSerialPort ;
/// <summary>
/// Polls all serial port and check for our device connected or not
/// </summary>
/// <returns>True: if our device is connected</returns>
public static bool Initialize()
{
var serialPortNames = SerialPort.GetPortNames();
foreach (var serialPortName in serialPortNames)
{
try
{
_arduinoSerialPort = new SerialPort(serialPortName) { BaudRate = 9600 };
_arduinoSerialPort.Open();
_arduinoSerialPort.DiscardInBuffer();
_arduinoSerialPort.Write(new byte[] { (int)SerialSignal.SendSync }, 0, 1);
var readBuffer = new byte[1];
Thread.Sleep(500);
_arduinoSerialPort.ReadTimeout = 5000;
_arduinoSerialPort.WriteTimeout = 5000;
_arduinoSerialPort.Read(readBuffer, 0, 1);
// Check if it is our device or Not;
if (readBuffer[0] == (byte)SerialSignal.ReceiveSync){
return true;
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception at Serial Port:" + serialPortName + Environment.NewLine +
"Additional Message: " + ex.Message);
}
// if the send Sync repply not received just release resourceses
if (_arduinoSerialPort != null) _arduinoSerialPort.Dispose();
}
return false;
}
公共局部類Form1:表單{SerialPort serial = new SerialPort(); 靜態SerialPort cport; 公共Form1(){InitializeComponent(); button1.Enabled = true; button2.Enabled = false; button3.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
int i;
try
{
string[] ports = SerialPort.GetPortNames();
foreach(string newport in ports)
{
cport = new SerialPort(newport, 9600);
cport.Open();
cport.WriteLine("A");
int intReturnASCII = serial.ReadByte();
char returnMessage = Convert.ToChar(intReturnASCII);
if (returnMessage == 'B')
{
button2.Enabled = true;
break;
}
else
{
cport.Close();
}
}
}
catch (Exception )
{
Console.WriteLine("No COM ports found");
}
}
我知道我來晚了,但是我創建了一個簡單且免費的C# NuGet庫,該庫允許主機PC和Arduino板之間進行交互!
ReadMe.txt文件中的示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.