简体   繁体   中英

Read serial data java in one line

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)", "");

在此处输入图片说明

Take a look at this. Since you are not running the String receivedData = serialPort.readString(event.getEventValue()); in a loop, you have to be getting a string. So I am assuming that the string you are getting has \\n after every character.
Is that assumption correct? Or is it something else?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM