2017-04-15 153 views
0

字符串Serial_Input必須包含與此A45F45A7(8字節)類似的序列號卡RFID(MIFARE)。有時當我將卡接近arduino的RFID閱讀器時,字符串就像這個A45F45(截斷),錯過任何字符。有更好的解決方案,而循環? (更優雅高效)使用Arduino IDE串行監視器,該卡的序列號是正確的。使用JAVA和jssc lib從Arduino串行端口讀取字符串

public static void connectionToCom(SerialPort serialPort, ComboBox<String> cbxComPort, TextArea txaMessages) throws SerialPortException 
{  
    int baudrate = 9600; int databits = 8; int stopbits = 1; int parity = 0; 

    serialPort.openPort() ; 
    serialPort.setParams(baudrate, databits, stopbits, parity) ; 

    String Serial_Input = null; 

    try { 
     while (true) 
     { 
      if (serialPort.readString() != null) 
      { 
       Serial_Input = serialPort.readString(8); 

       System.out.println("Card Serial: " + Serial_Input + "\n"); 
       //serialPort.closePort(); 
      } 
     } 
    } 
    catch (SerialPortException ex){ 
     txaMessages.appendText(ex.toString()); 
    } 
} 

Here the result image

回答

0

您可以使用該方法的addEventListener(SerialPortEventListener監聽器,INT面罩)。只要你通過串口接收到一個字節,它就會調用回調方法。

與不完整的字符串的問題可能是2個問題

  1. 在接收到整個字符串之前的代碼執行。爲了解決這個問題,你必須添加一個代碼來驗證你正在接收的字符串的長度。

  2. 您正在使用readString兩次。您可能會在第一次使用時丟失字符串的一些字節。