我的代碼有問題,我想讀取串行端口感謝DataReceivedHandler,但我只工作一次。此串行端口是一個EnOcean USB密鑰,當我按下按鈕時,它會從電子卡接收數據。數據發送是24個字節。第一次按按鈕時,它的工作狀態非常好,我收到了數據,但如果我再次按下,沒有任何事情發生,DataReceivedHandler看不到任何東西,也不會向我發送數據。多次讀取SerialDataPort
public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
//init serialport comport
SerialPort comport = (SerialPort)sender;
// Shortened and error checking removed for brevity...
int bytes = comport.BytesToRead;
string indata = comport.ReadExisting();
byte[] buffer = new byte[bytes];
comport.Read(buffer, 0, bytes);
HandleSerialData(buffer, comport);
}
HandleSerialData的作品,它在我的問題我沒有問題,我認爲,我讓代碼以防萬一。
public void HandleSerialData(byte[] respBuffer, SerialPort comport)
{
/*StringBuilder hex = new StringBuilder(respBuffer.Length * 2);
foreach (byte b in respBuffer)
hex.AppendFormat("{0:x2}", b);*/
string hex = "";
int n = 0;
byte[] ID_TIC;
ID_TIC = new byte[8];
for (int i = 12 ; i < 15; i++)
{
ID_TIC[n] = respBuffer[i];
n = n++;
}
hex = hex + BitConverter.ToString(ID_TIC).Replace("-",string.Empty);
string hex2 = hex.ToString();
Dispatcher.BeginInvoke((Action)(() => { EnOcean_Label.Content = ID_TIC; }));
Dispatcher.BeginInvoke((Action)(() => { EnOcean2_Label.Content = ID_TIC; }));
List<User> users = new List<User>();
users.Add(new User() { NumeroTIC = hex2, NumeroCNT1 = hex2, Date = DateTime.Now });
Dispatcher.BeginInvoke((Action)(() => { dgSimple.ItemsSource = users; }));
WriteTest(ID_TIC);
}
我們已經告訴過你如何在你的上一個問題中正確地做到這一點,你仍然在大幅度錯誤。調用ReadExisting()*和* Read()根本沒有意義,因爲ReadExisting已經清空了接收緩衝區,所以你永遠不會從Read()中獲得任何東西。而且你還沒有計算字節數,這是一個很難的要求,你不能忽略Read()的返回值。請一個團隊成員來幫助你。 –