我有一個arduino & c#項目。我有一個port_DataReceived
監聽器。通常情況下,它工作正常。但是,每當我關閉serialPort1
並再次打開時,它會給我一個錯誤。C#port_DataReceived無法正常工作
這裏的聽衆:
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (connect)
{
for (int i = 0; i < (10000 * serialPort1.BytesToRead)/serialPort1.BaudRate; i++);
//Delay a bit for the serial to catch up
String comingValue = serialPort1.ReadExisting();
Console.WriteLine(comingValue);
String rslt = comingValue[0].ToString(); // This line give me an error
}
}
以下是錯誤:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsFormsApplication1.exe
我檢查了comingValue
兩次是11
。第一次工作但第二次不起作用。我不知道爲什麼。如果有人知道爲什麼,請幫助我。謝謝。
對於()循環是毫無意義的,只需將其刪除即可。您沒有關注e.EventType屬性。因此不能假設ReadExisting()總是返回一個非空字符串。只需檢查字符串的Length屬性即可覆蓋所有底座,即使是扭曲的駕駛員。 –