2017-04-15 82 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两次。您可能会在第一次使用时丢失字符串的一些字节。