// This sketch uses the jSerialComm library to detect when a serial device
// is connected or disconnected. It displays the connection status on the screen.
// Requires the jSerialComm-2.11.2.jar file from here:
// https://fazecast.github.io/jSerialComm/
import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortEvent;
import com.fazecast.jSerialComm.SerialPortDataListener;
// Variables for the serial port object
private SerialPort serialPort;
// Standard Processing setup function
public void setup() {
size(400, 300, P2D);
surface.setTitle("Serial Disconnect Detector");
// Find and select the first available port
SerialPort[] commPorts = SerialPort.getCommPorts();
if (commPorts.length == 0) {
System.out.println("No serial ports found.");
return;
}
// Select the first port found
serialPort = commPorts[0];
// Configure and open the port
serialPort.setBaudRate(9600);
if (!serialPort.openPort()) {
serialPort = null;
return;
}
// Add an event listener to detect disconnection
serialPort.addDataListener(new SerialPortDataListener() {
@Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_PORT_DISCONNECTED;
}
@Override
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() == SerialPort.LISTENING_EVENT_PORT_DISCONNECTED) {
System.out.println("Port " + event.getSerialPort().getSystemPortName() + " WAS DISCONNECTED.");
// Clean up: set the port variable to null
serialPort = null;
}
}
});
}
// Standard Processing draw function. This loop updates the screen.
public void draw() {
background(240);
textAlign(CENTER, CENTER);
if (serialPort != null && serialPort.isOpen()) {
fill(0, 150, 0);
textSize(24);
text("Connected", width/2, height/2);
} else {
fill(150, 0, 0);
textSize(24);
text("Disconnected", width/2, height/2);
}
}
I did not explore beyond this.
I have used this library in the past for serial communications.