首页 > 解决方案 > JSerialComm Not Reading Whole String from Arduino

问题描述

I am using jSerialComm with my Java application to receive data from an Arduino. However, the Java program is only reading incoming "bytes". This isn't good because my Arduino is printing a long string, and I want the Java app to read the whole string without losing any info. My Arduino sends the data string twice a second.

I am on Windows 10 with JDK 13, using IntelliJ, Adruino IDE 1.8.10.

Currently the String is very long with a potential for size changes, so I can't just read a certain number of bytes.

I am even currently printing the string with a # at the front and a * at the end. My design is currently losing data somehow though, only getting an acceptable string maybe 1 in 10 strings sent.

    byte[] newData = new byte[comPort.bytesAvailable(0];
    int numRead = comPort.readBytes(newData, newData.length);
    stringBuffer = new String(newData,0,numRead);
    if (stringBuffer.startsWith("#"))
    {
         serialString+=stringBuffer;
         while (!stringBuffer.endsWith("*")
         {
              numRead = comPort.readBytes(newData, newData.length);
              stringBuffer = new String(newData,0,numRead);
              serialString+=stringBuffer;
         }

         //double check it is the proper format
         if (serialString.startsWith("#") && serial.String.endsWith("*")
         {
              //do stuff
         }
         serialString = "";
    }

Is there a method besides readBytes() I can use? I know I can use the getInputStream(), but I am uncertain where to go from there.

Thank you so much in advance.

标签: javaarduino

解决方案


想到两个问题。

1) 什么是仅在编写完整消息时才调用您的代码的同步方法?当 Arduino 只写了部分消息时,是什么阻止了代码运行?

2)你有任何类型的流量控制设置吗?Arduino 需要做的就是编写一个长字符串,但 PC 端代码需要将其接收到可能的多个缓冲区中。如果您使用的是内置硬件串行端口,那么您可能只能通过单个 PC 中断接收 16 个左右的字符。然后该缓冲区由操作系统通过操作系统驱动程序发送到您的应用程序。如果您使用的是 USB 转串口适配器,则可能会发生类似的问题,即长字符串被分成多个缓冲区,然后通过操作系统驱动程序发送到您的程序。您的程序不需要了解所有这些“幕后”缓冲区管理,但它可能会导致您的 PC 偶尔需要 Arduino 暂停发送数据。这就是软件握手协议的目的。

上述两个问题中的任何一个都可能导致您偶尔错过某个角色。它们不是串行通信故障的唯一来源,但它们是您的系统设计应该解决的问题。


推荐阅读