I’m trying to create a code that works with arduino by sending commands back and forth between the two. Processing is receiving commands from arduino easily enough but Processing is giving error “RuntimeException: Error writing to serial port COM4: Port not opened” when trying to write to serial.
import processing.video.*;
import processing.serial.*;
Serial port;
Capture camera;
String filePath = "C:/Users/Junor/OneDrive/Desktop/Pictures/";
String pictureCue = "Picture";
String readyCue = "Readying";
String serialRead = null;
int lf = 10;
int counter = 1;
Boolean pictureFlag = false;
void setup() {
  // Initialize port
  port = new Serial(this, Serial.list()[1], 9600);
  port.clear();
  serialRead = port.readStringUntil(lf);
  serialRead = null;
  
  // Call serialReady until return true
  while(serialReady(port) == false) {}
  // Let function serialEvent run
  pictureFlag = true;
  port.bufferUntil('\n');
  
  // Initialize live camera feed
  size(640,480);
  camera = new Capture(this, Capture.list()[0]);
  camera.start();
}
void captureEvent(Capture camera) {
  camera.read();
  
}
void draw() {
  image (camera, 0, 0);
}
void serialEvent(Serial port) {
  if (pictureFlag == false) {
    noLoop();
    exit();
  }
  else {
    loop();
    
    port.bufferUntil(lf);
    if (port.available() > 0) {
      serialRead = port.readString();
    
      if (serialRead != null) {
        if (serialRead.equals(pictureCue) == true) {
          println(serialRead);
          println("Picture " + counter);
          saveFrame(filePath + counter + ".png");
          counter++;
          port.write("Saved\n");
        }
      }
    }
  }
}
Boolean serialReady(Serial port) {
  Boolean readyFlag = false;
  port.bufferUntil(lf);
  if (port.available() > 0) {
    serialRead = port.readString();
    print(serialRead);
    if (serialRead != null) {
      if (serialRead.equals(readyCue) == true) {
        readyFlag = true;
      }
      else {readyFlag = false;}
    }
  }
  if (readyFlag == true)
    print ("readyFlag " + readyFlag);
// *
// *
  port.write("Ready\n");    // Calling the error here
// *
// *
  return readyFlag;
}
Clearly, “Port not opened” doesn’t mean what I think it means, since in order to get to the spot that is flagged as the error it has to receive a specified string to move on. Is there something I declared incorrectly or out of order or something? I know I’ve had a problem like that in the past.