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

Read String from Arduino serial port with JAVA and jssc lib

字符串Serial_Input 必须包含序列号卡 RFID (MIFARE),例如 A45F45A7(8 字节)。有时当我将卡靠近 arduino 的 RFID reader 时,字符串就像这样 A45F45(截断的),错过任何字符。有比 while 循环更好的解决方案吗? (更优雅,更高效)使用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

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

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

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

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