重新连接处理串行端口 [英] Reconnect Serial Port on Processing

查看:194
本文介绍了重新连接处理串行端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以及我在读从Arduino的输入,串行端口,但连接中断,可能会出现处理,在这种情况下,如何重启我这方面?

I'm using processing and I'm reading inputs from Arduino with a serial port but connection drop may occur, in this case how to I reopen this connection?

推荐答案

您可以赶上通过Serial.java抛出RuntimeExceptions,这一般表明串口不再可用。在这一catch块,那么,你就可以开始查询串行口;一旦它可以让你重新实例到您的序列实例,端口再次可用(例如USB电缆插回去了),你是在后面的比赛。

You can catch RuntimeExceptions thrown by Serial.java, which generally indicate the serial port is no longer available. Within that catch block, then, you can start polling the serial port; once it allows you to reinstantiate your Serial instance, the port is again available (e.g. the USB cable is plugged back in) and you're back in the game.

Serial serial;
boolean serialInited;

void setup () {
    initSerial();
}

void draw () {
    if (serialInited) {
        // serial is up and running
        try {
            byte b = serial.read();
            // fun with serial here...
        } catch (RuntimeException e) {
            // serial port closed :(
            serialInited = false;
        }
    } else {
        // serial port is not available. bang on it until it is.
        initSerial();
    }
}

void initSerial () {
    try {
        serial = new Serial(this, Serial.list()[0], BAUD_RATE);
        serialInited = true;
    } catch (RuntimeException e) {
        if (e.getMessage().contains("<init>")) {
            System.out.println("port in use, trying again later...");
            serialInited = false;
        }
    }
}

,而不是试图重新连接的每个的框,你可能反而要使用限制重新连接尝试的频率计数器。 (例如数到10,再试一次,根据需要重复。)不应该的问题多,但不知道啊,撞硬的串行端口上可能会有意想不到的副作用,由于东西我知之甚少。

Rather than attempting to reconnect every frame, you might instead want to use a counter that limits the frequency of reconnection attempts. (e.g. count to 10, try again, repeat as needed.) Shouldn't matter that much, but dunno...banging that hard on the serial port may have unexpected side effects due to something I know little about.

这篇关于重新连接处理串行端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆