I'm making a project with a rs485 module.
Every time the module sends data to my com port i want to catch that data.
And that's works, I can catch it. But when I catch it I see it in multiple lines.
My data starts every time with *
and ends with #
.
Can you help my to catch the data in only 1 line ? Thanks !
public void serialEvent(SerialPortEvent event) {
//if(event.isRXCHAR() && event.getEventValue() > 0) {
try {
String receivedData = serialPort.readString(event.getEventValue());
while (receivedData.charAt(0) == '#') {
receivedData = receivedData.substring(1, receivedData.length());
}
System.out.println("Received response from port: " + receivedData);
} catch (SerialPortException ex) {
System.out.println("Error in receiving response from port: " + ex);
}
//}
}
You need to read until you get the initial *
, and then read until you get the final #
":
String ch;
StringBuffer data = new StringBuffer();
while (!(ch = serialPort.readString(1)).equals("*"))
;
while (!(ch = serialPort.readString(1)).equals("#"))
data.append(ch);
return data.toString();
You need to add error and EOS handling to this, of course.
If the problem is that you are iterating receivedData as a char array then you can do this
receivedData = receivedData.substring(receivedData.indexOf('*'), receivedData.indexOf('#'));
If you are getting new line characters in the input just use
receivedData = receivedData.replaceAll("(\\n)", "");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.