ademar111190
ademar111190

Reputation: 14505

Reconnect Serial Port on Processing

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?

Upvotes: 1

Views: 4264

Answers (2)

ericsoco
ericsoco

Reputation: 26253

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;
        }
    }
}

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.

Upvotes: 4

ZnArK
ZnArK

Reputation: 1541

In the Arduino IDE, you would have to close the Serial port monitor and then go back to [Tools] -> [Serial Port] to re-select your serial port.

This is because when you disconnect the cable, you are removing the serial device you were previously using. Linux handles this better than windows, but either way, it plays havoc with the serial monitor.

Instead of removing the USB cable, you should press the reset button on the board to restart your program.

Also, keep in mind that many Arduinos have an Auto-Reset on Serial communication "feature". I posted directions to a work-around here.

enter image description here

Upvotes: 3

Related Questions