【发布时间】:2017-03-26 17:04:19
【问题描述】:
我编写了一个 Java 程序来读取 COM 端口并从 Arduino UNO 获取数据,但它只运行了有限的次数并意外停止。
我正在使用这个 jSerialComm library 。程序如下:
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");
}
}
它在平均运行 40-50 行串行输入后停止。请帮助我。
【问题讨论】:
-
它可能被阻止等待更多数据。它使用的是什么分隔符?
-
数据源源不断地来自 arduino。我尝试在 python 中编写一个类似的程序,它会不停地读取和打印。但是我在 Java 中需要它,不幸的是它不能维持阅读过程。
标签: java arduino serial-port