How to close serial port when window is closed

I am using serial port for building GUI with ControlP5.
I open serial port in setup() function. i.e. tha start of program.

I want to close the serial port when user closes the window.
I know that port.close() can be used to close the serial port.

But I don’t know where to use this command as I don’t know what is executed when the user closes the window.
Please help.

You can override exit():

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

Give it a try adding your code.

References:

:)

1 Like

Hi

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

Thank you,

I am new to java.

I don’t understand where to add myPort.stop(); in this code?
Please help.

I found the solution.

Credit : Found info here

Here is the code:

void exit() {
    println("Exiting program");
    myPort.stop();  // stoping serial port.
   //your Code above. 
   super.exit();
}
1 Like