【问题标题】:Java Program Stops Midway when Reading Com Port of ArduinoJava程序在读取Arduino的Com端口时中途停止
【发布时间】: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


【解决方案1】:

试试这个,在行中

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

使用 TIMEOUT_SCANNER 而不是 TIMEOUT_READ_SEMI_BLOCKING。我有同样的问题。此解决方案已在显示此代码的 youtube 视频的 cmets 部分中介绍。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2011-01-10
    相关资源
    最近更新 更多