如果java程序应该连续地从串行通信接收数据,但是程序现在遇到延迟或延迟,该怎么办?

yyyllmsg  于 2021-07-08  发布在  Java
关注(0)|答案(0)|浏览(258)

我正在使用arduino通过serialcomm连接到java netbeans。我的java程序应该持续接收数据,串行端口必须持续打开。我现在正在经历程序的延迟或延迟。我想这可能是因为计时器,所以我试图删除它。但是当我这样做的时候,串行端口不再打开了。
我应该怎么做来消除延迟或程序被减慢?也许有其他方法可以做到这一点,比如改变我的动作监听器,或者让它不使用计时器连续读取串行端口。
提前感谢您的回答!

Timer timer ;   
ActionListener readRF = new ActionListener() {
    @Override
         public void actionPerformed(ActionEvent e) {
                String str;
 SerialPort serialPort = new SerialPort("COM3");
//In the constructor pass the name of the port with which we work

try {
    //Open port
    serialPort.openPort();

    serialPort.setParams(SerialPort.BAUDRATE_9600,
            SerialPort.DATABITS_8,
            SerialPort.STOPBITS_1,
            SerialPort.PARITY_NONE);

    Thread.sleep(1000);//Very important !!!

    //Read data from port
    for (int i = 0; i < 30; i++) {
        str = serialPort.readString();

        if (str != null) {
                System.out.println(str);
            if(str.contains("15538849")){
            queue1.setText(String.valueOf(q.Table1Peek()));
            }else if(str.contains("15538850")){
            q.Table1DeQueue();    
            queue1.setText(String.valueOf(q.Table1Peek()));
            }
        }

        Thread.sleep(100);
    }

    //Closing the port
    serialPort.closePort();

} catch (SerialPortException ex ) {
    System.out.println(ex);
} catch (InterruptedException ex) {
    System.out.println(ex);
}
        }

};
                timer = new Timer(1000,readRF);
                timer.setInitialDelay(0);
                timer.start();

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题