java - 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.
解决方案
想到两个问题。
1) 什么是仅在编写完整消息时才调用您的代码的同步方法?当 Arduino 只写了部分消息时,是什么阻止了代码运行?
2)你有任何类型的流量控制设置吗?Arduino 需要做的就是编写一个长字符串,但 PC 端代码需要将其接收到可能的多个缓冲区中。如果您使用的是内置硬件串行端口,那么您可能只能通过单个 PC 中断接收 16 个左右的字符。然后该缓冲区由操作系统通过操作系统驱动程序发送到您的应用程序。如果您使用的是 USB 转串口适配器,则可能会发生类似的问题,即长字符串被分成多个缓冲区,然后通过操作系统驱动程序发送到您的程序。您的程序不需要了解所有这些“幕后”缓冲区管理,但它可能会导致您的 PC 偶尔需要 Arduino 暂停发送数据。这就是软件握手协议的目的。
上述两个问题中的任何一个都可能导致您偶尔错过某个角色。它们不是串行通信故障的唯一来源,但它们是您的系统设计应该解决的问题。
推荐阅读
- python - 无法将 numpy 模块导入 python 文件,但它适用于终端
- python - Tensorflow 已下载但未安装在 ubuntu 服务器上
- java - java selenium:想做一个采购机器人。我在页面上的 JavaScript 按钮有问题
- javascript - 清除材料设计下拉值会导致错误
- java - 用equals方法测试Java中对象的相等性
- python - HTTPS - 如何实际解密客户端请求
- angular - 不能将同步融合用于角度
- node.js - Pug、Marked 和 NodeJs 问题
- javascript - D3 区域图未显示数据数组中的第一个索引对象
- html - 是否可以让 iOS Safari 上传原始 HEIC 照片而不进行 JPEG 转换?