2017-04-18 68 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'应该在那个确切的行之后(如果它发出命令的话) –