且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取完整的行 Java 串行端口

更新时间:2023-10-19 21:50:46

要解决上述问题,您需要将收到的字符串连接到另一个字符串中,该字符串累积从 readString() 函数收到的字符串片段,该函数位于serialEvent 处理程序.因为它是 owm 线程,所以它获得一定数量的 CPU 时间来获取串行数据,因此它有效地获取串行端口输入数据的部分顺序读取.因此,此示例将部分输入放在一起以创建整体"输入.

To fix the stated problem you need to concatenate the strings you receive into another string that accumulates the string fragments you receive from the readString() function, which is in the serialEvent handler. Because it is it's owm thread it gets a certain amount of cpu time to get serial data so it effectively gets partial sequential reads of the serial port input data. So this example puts the partial inputs together to create the "whole" input.

String serialString;

因此在 serialEvent 处理程序中:

So within the serialEvent handler:

try {
serialStringFragment = serialPort.readString();
serialString.concat(serialStringFragment);
}

无论是从 readString() 获得的字符串还是累积字符串,都可以扫描像 eol 条件这样的标记.例如:

Either the string you get from readString() or the accumulation string can be scanned for tokens like eol condition. For Example:

String [] dlLines = serialString.split("\r\n");

会将每一行拆分为 dlLines 字符串数组中的一个元素.

will break each line out to an element in the dlLines string array.

但是我发现如果我的目标设备有固定长度的输出,效果会更好:

However I have found that if I have fixed length output from my target device this works better:

serialPort.readString(int bytecount);

内联写入串行字符串,消除serialEvent 处理程序.

inline with the write serial string, eliminating the serialEvent handler.

这有点做作,但换句话说:

This is a bit contrived but In other words:

String expectedStringLength "0100071CA79215021803164442180000";
int serialstrlen = expectedStringLength.length();

因此,serialstrlen 显然应该成为每个预期行的常量.

So the serialstrlen should obviously become constants for each expected line.

serialPort.writeString("N\r\n");
serialPort.readString(serialstrlen+2); // assuming cr lf 

应该给你第一行.

将 readString() 放入循环中,根据预期的字符串更改 serialstrelen 参数值.检查字符串的替代内容以进行错误处理.这对我有用.

Put the readString() in a loop, change serialstrelen argument value according to the expected strings. Check the strings for alternate content for error handling. This has worked for me.