# Error writing to serial: port not opened after already reading from serial

**URL:** https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521
**Category:** Electronics (Arduino, etc.)
**Created:** [March 14, 2021, 3:48am UTC](https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521 "2021-03-14T03:48:30Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![junorox](https://avatars.discourse-cdn.com/v4/letter/j/94ad74/32.png) [@junorox](https://discourse.processing.org/u/junorox)
#### Post date: [March 14, 2021, 3:48am UTC](https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521/1 "2021-03-14T03:48:30Z")

</div>

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.

```auto
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.

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [March 15, 2021, 12:40am UTC](https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521/2 "2021-03-15T00:40:11Z")

</div>

Hello,

I was getting same error.

I added some brackets in the if() statement so you only did a _port.write()_ when readyFlag was true :

```auto
if (readyFlag == true)
    { // glv added
    print ("readyFlag " + readyFlag);
// *
    port.write("Ready\n"); // Calling the error here
    } // glv added
// *

```

After all that was said and done I did a rewrite and only used the _serialEvent()_ for handshaking and **not** the _serialReady(Serial port)_ and got this working.

I also used _trim()_ to clean up incoming serial strings:  
`if (serialRead.trim().equals("pictureCue") == true)`  
`:)`

I wrote some Arduino code to do the serial handshaking .

`:)`

---

<div class="post-metadata">

### Author: ![junorox](https://avatars.discourse-cdn.com/v4/letter/j/94ad74/32.png) [@junorox](https://discourse.processing.org/u/junorox)
#### Post date: [March 15, 2021, 1:36am UTC](https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521/3 "2021-03-15T01:36:45Z")

</div>

Fantastic, exactly what I needed! I took your suggestions and added trim functions, as well as condensed it all into serialEvent. Turned out much cleaner this way in the end as well, and gets rid of my loop problem.  
Thanks you so much, this had been bugging me for a day or two now. That one step has practically finished the project

---

<div class="post-metadata">

### Author: ![glv](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/glv/32/18785_2.png) [@glv](https://discourse.processing.org/u/glv)
#### Post date: [March 15, 2021, 1:46am UTC](https://discourse.processing.org/t/error-writing-to-serial-port-not-opened-after-already-reading-from-serial/28521/4 "2021-03-15T01:46:11Z")

</div>

> [@junorox](#):
>
> Fantastic, exactly what I needed!

Great!

I also use a lot of println() statements to see progress of code and that really helps debugging code.

I have a few other topics on serial communication with hints and tips that may be of interest.

Have fun!
