【问题标题】:Am I reading the Arduino incoming data the wrong way using jSerialComm?我是否使用 jSerialComm 以错误的方式读取 Arduino 传入数据?
【发布时间】:2020-03-21 19:33:25
【问题描述】:

我正在编写一个必须与我的 Arduino UNO 通信的 JavaFX 应用程序。为此我使用 jSerialComm 库。

只是为了测试目的,我已经将一个非常简单的草图上传到我的 Arduino,它每 2 秒向串行打印一个“Hello”字样:

void setup() {
    //put your setup code here, to run once:
    Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000);
  Serial.print("Hello");
}

在我的 JavaFX 场景中,我用这个读取传入的数据:

public void setDevice(SerialPort device) {
    this.device = device;
    device.openPort();
    device.addDataListener(new SerialPortDataListener() {
        @Override
        public int getListeningEvents() {
            return SerialPort.LISTENING_EVENT_DATA_RECEIVED;
        }

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            if (serialPortEvent.getEventType() == SerialPort.LISTENING_EVENT_DATA_RECEIVED){
                byte [] data = serialPortEvent.getReceivedData();
                String msg = new String(data);
                System.out.println(msg);
            }
        }
    });
}

我可以从 Arduino 读取数据,但它以一种奇怪的方式出现。就像字符串以 2 个不同的字符串发送一样。这是控制台输出的图像:

我做错了吗?非常感谢!

【问题讨论】:

    标签: java arduino serial-port


    【解决方案1】:

    您在默认 = 非阻塞模式下使用 jSerialComm。那么会发生什么(作为伪代码步骤)

     LISTENING_EVENT_DATA_RECEIVED triggered
     get the char H
     get the char e
     Because we are nonBlocking we have to move on in the program
     Print what we have so far -> HE
    .... do other stuff or check if other stuff has to be processed
    LISTENING_EVENT_DATA_RECEIVED triggered
     get the char L
     get the char L
     get the char O
     Because we are nonBlocking we have to move on in the program
     Print what we have so far -> LLO
     .... do other stuff or check if other stuff has to be processed
    

    所以你可以做两件事 -> 将模式更改为例如接收时阻塞(确保适当的超时以防止死锁)或重写函数(我的首选方式)以检查通信流中的结束终止符,然后处理缓冲区的内容(应以非阻塞方式实现)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2019-12-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 2014-06-15
    相关资源
    最近更新 更多