使用JAVA和jssc lib从Arduino串口读取字符串

时间:2017-04-15 10:39:39

标签: java arduino serial-port jssc

String Serial_Input必须包含一个序列号卡RFID(MIFARE),如A45F45A7(8字节)。有时当我接近arduino的RFID读卡器时,字符串就像这样的A45F45(截断),错过任何字符。有一个更好的解决方案,虽然循环? (更优雅,更高效)使用Arduino IDE Serial Monitor,卡的序列号是正确的。

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

1 个答案:

答案 0 :(得分:0)

您可以使用方法addEventListener(SerialPortEventListener listener,int mask)。每当通过serialPort收到一个字节时,它就会调用一个回调方法。

不完整字符串的问题可能是2个问题

  1. 代码在收到整个字符串之前执行。要解决此问题,您必须添加代码以验证您收到的字符串的长度。

  2. 您正在使用readString两次。在第一次使用时,您可能会丢失字符串的一些字节。