[英]Unable to come out of the loop while reading data from serial communication port (COM1)
I am using https://github.com/rm5248/JavaSerial and developed a project for writing and reading data from serial port. 我正在使用https://github.com/rm5248/JavaSerial并开发了一个用于从串行端口写入和读取数据的项目。 Both are happening perfectly fine, but I am not able to find the last byte of information and come out of the loop. 两者都进行得很好,但是我无法找到信息的最后一个字节并退出循环。
Any pointers here are highly appreciated. 非常感谢这里的任何指针。
portName = currPortId.getName();
// This would be COM1, COM2, etc on Windows
// SerialPort s = new SerialPort(portName);
SerialPort s = new SerialPort("COM1");//, SerialPort.NO_CONTROL_LINE_CHANGE);
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
String st = "";
st = "5230" + 31 + String.format("%02X", new Object[] { Integer.valueOf(179) })
+ String.format("%02X", new Object[] { Integer.valueOf(83) });
os.write(hexStringToByteArray(st + "0D"));
System.out.println("Data written");
byte[] dataRead = new byte[753];
int bytesRead = 0;/* = is.read(dataRead); */
while (bytesRead != -1 /*|| dataRead.equals("end")*//*equals("353535")*/) {
/*
* System.out.println("Data in string format is " + new
* String(dataRead, "UTF-8").replace("\n", "").replace("\r",
* "").trim());
*/
// bytesRead = is.read(dataRead);
bytesRead = is.read(dataRead);
Thread.sleep(90L);
System.out.println("bytesRead value is " + bytesRead);
String theString = new String(dataRead, "UTF-8").replace("\n", "").replace("\r", "").trim();
System.out.println("theString value is " + theString);
/*
* sb[0].append(theString); data.add(sb[0].toString()); if
* (dataRead[(dataRead.length - 1)] == 13) {
* data.add(sb[0].toString()); sb[0] = new StringBuilder(); }
*/
data.add(theString);
System.out.println("data value is " + data);
}
I tried some of the things like 我尝试了一些诸如
while (bytesRead != -1)
while(dataRead.equals("end"))
while(dataRead.equals("353535"))
But was not useful 但是没用
The InputStream
that you get back from the SerialPort
follows the same rules that a normal InputStream
does, which means that is.read()
is a blocking call. 从SerialPort
取回的InputStream
遵循与普通InputStream
相同的规则,这意味着is.read()
是阻塞调用。 The only time that is.read()
will return -1 for the end of input is when the serial port is closed. 在输入结束时, is.read()
唯一会返回-1的时间是在关闭串行端口时。
If you want to read exactly 753 bytes, you should break out of your loop after you have read that number of bytes. 如果您想精确地读取753个字节,则在读取该字节数后应退出循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.