It’s because try - catch
failed and myPort
remained empty. By the way I couldn’t get what you mean, but does the code run if the Arduino is connected, and crashes when it’s not connected?
If you want to give time for the user to connect USB, I suggest moving the initialization part to draw
instead. Pseudo code would be
boolean isConnected = false;
void draw() {
if(isConnected == false) {
try {
// serial connection
...
if(success) {
isConnected = true;
}
else {
// delay
...
}
} catch (e) {
// delay
...
}
}
else {
// do the usual process of serial communication and drawing
...
}
}
and this gives flexibility to go back to the connection process once the Arduino is accidentally disconnected (in theory. I don’t know if it actually works like that, though). Also for where I wrote delay
, it would be even better if you avoid delay
function and check the elapsed time and say
if(currentTime - lastTime > 5000) {
// do something after 5 sec passed
}
so that there is no interruption in the animation frame (you can display, like “reconnecting in 2 sec”