2015-11-30 93 views
0

我有一個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。第一次工作但第二次不起作用。我不知道爲什麼。如果有人知道爲什麼,請幫助我。謝謝。

+0

對於()循環是毫無意義的,只需將其刪除即可。您沒有關注e.EventType屬性。因此不能假設ReadExisting()總是返回一個非空字符串。只需檢查字符串的Length屬性即可覆蓋所有底座,即使是扭曲的駕駛員。 –

回答

1

您應該檢查字符串IsNullOrEmpty()。您正試圖按索引讀取第一個字符。當comingValue中沒有數據時。你會得到一個索引超出界限。只讀的第一個字符時,居然有一個(或多個)

String comingValue = serialPort1.ReadExisting(); 
Console.WriteLine(comingValue); 
String rslt = ""; 
if(!string.IsNullOrEmpty(comingValue)) 
    rslt = comingValue[0].ToString(); 

這是一種不好的做法啄用於延遲...

for (int i = 0; i < (10000 * serialPort1.BytesToRead)/serialPort1.BaudRate; i++); 

這將在運行不同其他電腦。嘗試Thread.Sleep(10);什麼的。

+0

但是,這條線的作品我可以看到輸出: Console.WriteLine(comingValue); –