2016-08-11 186 views
0

我有使用USB串行電纜HL-340(PL-2303還測試)連接到串行端口器件樹莓PI奇怪的結果

的裝置需要1字節命令,並應與2字節回覆(OK,這是非常簡單的設備,很容易學習的協議:))

我的代碼:

[...] 
     final int[] status = this.serialPort.getLinesStatus (); 
     final StringBuilder sb = new StringBuilder ("Lines Status:"); 
     final String[] name = new String[] { "CTS", "DSR", "RING", "RLSD" }; 
     for (int i = 0; i < status.length; i++) 
      sb.append ((i > 0) ? "," : "").append (name [i]).append (':').append (status [i]); 
     System.out.println (sb.toString ()); 
     System.out.println ("flowcontrol:" + this.serialPort.getFlowControlMode ()); 
     this.serialPort.purgePort (SerialPort.PURGE_RXCLEAR | SerialPort.PURGE_TXCLEAR); 

     synchronized (this) 
     { 
      System.out.println ("1) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ()); 
      this.serialPort.addEventListener (this); 
      this.serialPort.setEventsMask (SerialPort.MASK_RXCHAR); 
      this.serialPort.writeBytes (COMMAND); 
      wait (3000); // wait 3 seconds for reply 
      this.serialPort.removeEventListener (); 
      System.out.println ("2) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ()); 
      final int n = this.serialPort.getInputBufferBytesCount (); 
      if (n > 0) 
      { 
      this.serialPort.readBytes (n); // purge garbage data? 
      System.out.println ("3) getInputBufferBytesCount():" + this.serialPort.getInputBufferBytesCount ()); 
      } 
     } 
     if ((this.data == null) && (this.error == null)) 
      this.error = "no response from device"; 
[...] 

和回調代碼:

@Override 
public final void serialEvent (final SerialPortEvent event) 
{ 
    synchronized (this) 
    { 
    try 
    { 
     final int val; 
     if (event.isRXCHAR ()) 
     if ((val = event.getEventValue ()) == 2) // the reply is 2 bytes 
      this.data = this.serialPort.readBytes (2); 
     else 
      this.error = "unexpected value:" + val; 
     else 
     this.error = "unexpected event:" + event; 
    } 
    catch (final Throwable x) 
    { 
     this.error = x.toString (); 
    } 
    finally 
    { 
     notify (); 
    } 
    } 
} 

結果是非常詭異莫測 :(我希望只有2個字節爲從設備的答覆,但串行端口通知我提供更多的數據讀取:

Lines Status:CTS:0,DSR:0,RING:0,RLSD:0 
flowcontrol:0 
1) getInputBufferBytesCount():0 
2) getInputBufferBytesCount():544 
3) getInputBufferBytesCount():0 
java.lang.Throwable: unexpected value:192 

Lines Status:CTS:0,DSR:0,RING:0,RLSD:0 
flowcontrol:0 
1) getInputBufferBytesCount():0 
2) getInputBufferBytesCount():512 
3) getInputBufferBytesCount():0 
java.lang.Throwable: unexpected value:192 

Lines Status:CTS:0,DSR:0,RING:0,RLSD:0 
flowcontrol:0 
1) getInputBufferBytesCount():0 
2) getInputBufferBytesCount():32 
3) getInputBufferBytesCount():0 
java.lang.Throwable: unexpected value:32 

什麼是問題?我應該更改哪些端口設置?

回答

0

假設您在等待2個字節的回覆,現在收到回覆之後,打印緩衝區中的所有字節以查看這是垃圾數據(特殊的非打印字符)還是有效數據。這將給你更多的見解和下一步行動項目進一步進展。