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.