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?
-
what's wrong with the method you established the connection in the first place?Matti Lyra– Matti Lyra2012-09-24 19:30:27 +00:00Commented Sep 24, 2012 at 19:30
-
if I remove the usb cable, for example, and reconnect it, I cannot reconnect the serial port without close and reopen the software.ademar111190– ademar1111902012-09-24 19:34:08 +00:00Commented Sep 24, 2012 at 19:34
-
Please add to your question what things make the connection drop (including USB unplugging and any other situations if applicable)ZnArK– ZnArK2012-09-24 21:30:04 +00:00Commented Sep 24, 2012 at 21:30
2 Answers
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.
Comments
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.
