0
votes

I have written a Java program to read a COM port and get data from Arduino UNO, but it only runs for a limited number of times and stops unexpectedly.

I am using this jSerialComm library . The program is as below:


import com.fazecast.jSerialComm.*;
import javax.swing.*;
import java.util.Scanner;

/**
 *
 * @author Lumbani
 */
public class SmartFarm {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        SerialPort ports[] = SerialPort.getCommPorts();

        System.out.println("Select a port:");

        int i=1;
        for(SerialPort port : ports){
            System.out.println(i++ +": "+port.getSystemPortName());
        }

        Scanner s = new Scanner(System.in);
        int choiceport= s.nextInt();

        SerialPort port = ports[choiceport - 1];

        if(port.openPort()){
            System.out.println("Successfully opened port");
        }
        else{ 
            System.out.println("Unable to open the port");
            }
        port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING,100,0);

        Scanner data = new Scanner(port.getInputStream());

        int line =1;

        while(data.hasNextLine()){
            int number = 0;

            try {number = Integer.parseInt(data.nextLine());
            line++;  
            System.out.println("Line "+ line +": "+number);  
            }
                catch(Exception e){System.out.println("Failed to get data");};

        }
        System.out.println("System run finished");
        }
        }

It stops after running, on average, serial input of 40-50 lines. Please assist me.

1
It's probably blocked waiting for more data. What is the delimiter it is using?Shane Wealti
The data comes nonstop from the arduino. I tried writing a similar program in python, and it reads and print non stop. However I need it in Java, which unfortunately is not sustaining the reading process.pupani3

1 Answers

0
votes

Try this, in the line

port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING,100,0);

Use TIMEOUT_SCANNER instead of TIMEOUT_READ_SEMI_BLOCKING. I had the same problem. This solution was presented in the comments section of the youtube video where this code was shown.