2017-04-18 57 views
0

我的代碼有問題,我想讀取串行端口感謝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); 


    } 
+0

我們已經告訴過你如何在你的上一個問題中正確地做到這一點,你仍然在大幅度錯誤。調用ReadExisting()*和* Read()根本沒有意義,因爲ReadExisting已經清空了接收緩衝區,所以你永遠不會從Read()中獲得任何東西。而且你還沒有計算字節數,這是一個很難的要求,你不能忽略Read()的返回值。請一個團隊成員來幫助你。 –

回答

0

發送字節之後你不打開一個串口(你需要這個以做):

//Last line of code that sends the hex-code 
System.Threading.Thread.Sleep(500) //Assuming you're starting with an open port 

...並等待答覆

或者:

//Last line of code that sends the hex-code 
comPortReadFunction() 

您的閱讀功能不應該有任何參數。你不需要有當你正在聽的COM端口

+0

好吧,經過幾次測試,發生這種情況,我的串口沒有連接(像是某種方式c​​omport.close();發生在我的代碼中的某處,但它沒有)在第一次電報 –

+0

後沒有包含完整的代碼所以我不能說這些。向我們展示一切。 –

-2

好參數,我知道爲什麼是我的問題,我的SerialPort未被定義爲靜態的,垃圾收集殺死它每次被稱爲

+0

'WriteTest(ID_TIC)'功能在哪裏? 'Thread.Sleep'應該在那個確切的行之後(如果它發出命令的話) –