I did some experimenting with this a while ago to close the serial port when closing the sketch.
This only works when you close sketch window with X
@Override
public void exit() {
if (surface.isStopped()) {
// exit immediately, dispose() has already been called,
// meaning that the main thread has long since exited
exitActual();
} else if (looping) {
// dispose() will be called as the thread exits
finished = true;
// tell the code to call exitActual() to do a System.exit()
// once the next draw() has completed
exitCalled = true;
} else { // !looping
// if not looping, shut down things explicitly,
// because the main thread will be sleeping
dispose();
// now get out
exitActual();
}
println("Exiting..."); // This is all I added!
}
void setSerialPort(String portName) {
// Close the port if it's currently open.
if (port != null) {
port.stop();
}
try {
// Open port.
port = new Serial(this, portName, 115200);
port.bufferUntil('\n');
// Persist port in configuration.
saveStrings(serialConfigFile, new String[] { portName });
}
catch (RuntimeException ex) {
// Swallow error if port can't be opened, keep port closed.
port = null;
}
}