Search code examples
javawhile-loopserial-port

How to break from a WHILE loop when reading from a serial port?


I have a while loop that reads from a serial port using a scanner and adds all the data it reads to a List<String>. My problem is I don't know how to exit the loop when I receive the data?

The data I receive in the loop is

[***, REPORT, ***, MIB-Series, Currency, Counter, --------------------------------, Mar.6,2022,, 01:26, Station:1, Deposit, No.:, 2, Mixed, Mode, RSD, UV, MG, IR, --------------------------------, DENOM, UNIT, TOTAL, D10, 0, D, 0, D20, 0, D, 0, D50, 0, D, 0, D100, 0, D, 0, D200, 0, D, 0, D500, 0, D, 0, D1000, 0, D, 0, D2000, 0, D, 0, D5000, 0, D, 0, --------------------------------, TOTAL, 0, D, 0, --------------------------------, m3]

And the code that I use is

public static List<String> readFromPort(SerialPort serialPort) {

    Scanner sc = new Scanner(serialPort.getInputStream());

    List<String> line = new ArrayList<>();
    
    while (sc.hasNextLine()) {
        line.add(sc.next());
    }
    sc.close();
    return line;
}

I tried adding this condition to WHILE loop && !line.contains("m3") but for some reason, I then have to press "Send" on the serial device twice to receive data. If I use some other string from the list it works fine(I press "Send" only once), but then I don't receive the complete data.

Any ideas what else to try?

NOTE: I'm using JSerialComm library.

EDIT: The String at the end of List is like in the screenshot below, the two unrecognized characters are deleted automatically when I post the question.

enter image description here

enter image description here


Solution

  • I solved this using this code:

    public static List<String> readFromPort(SerialPort serialPort) {
    
        Scanner sc = new Scanner(serialPort.getInputStream());
    
        List<String> line = new ArrayList<>();
    
        while (sc.hasNextLine()) {
            line.add(sc.next());
            if(line.contains("m3")){
                break;
            }
        }
        return line;
    }
    

    I added an IF statement inside the WHILE loop which contained the same condition as I previously used in WHILE loop. This solved my problem, and now I'm getting the correct data with only one click on "Send" from my device.

    Thanks everyone for your help.