【问题标题】:Read String from Arduino serial port with JAVA and jssc lib使用 JAVA 和 jssc 库从 Arduino 串口读取字符串
【发布时间】:2023-03-29 02:16:01
【问题描述】:

String Serial_Input 必须包含一个序列号卡 RFID (MIFARE),如 A45F45A7(8 字节)。有时当我将卡靠近 arduino 的 RFID 阅读器时,字符串就像这个 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

【问题讨论】:

    标签: java arduino serial-port jssc


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-08
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 1970-01-01
      相关资源
      最近更新 更多