1

The following code makes Arduino and Processing pass an 'A' back and forth like hot potato:

PROCESSING SENDS 'A' TO ARDUINO

import processing.serial.*; //import the Serial library
Serial mySerial;  //the Serial port object

void setup() 
{
  mySerial = new Serial(this, Serial.list()[7], 9600); //Pick whichever works
  mySerial.bufferUntil('\n');
}

void serialEvent( Serial mySerial) 
{
  println("writing A...");
  delay(1000);                   //How I defined this is not relevant. Trust me.
  mySerial.write('A');        //Send 'A' to Arduino
}

ARDUINO SENDS 'A' BACK TO PROCESSING

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  delay(1000);
  Serial.println('A');      //Send 'A' back to Processing
}

What happens? Well... the game works for about ten exchanges (how do I know? well I get the "writing A..." message five times, and my use of bufferUntil() tells me that each of those messages were prompted by receiving a Serial.println('A') from the Arduino) BUT then Processing interrupts with the following error:

Error, disabling serialEvent() for /dev/tty.usbmodem1421
null
java.lang.RuntimeException: Error reading from serial port /dev/tty.usbmodem1421: Port not opened
    at processing.serial.Serial.serialEvent(Unknown Source)
    at jssc.SerialPort$LinuxEventThread.run(SerialPort.java:1299)
Could not run the sketch (Target VM failed to initialize).
For more information, read revisions.txt and Help → Troubleshooting.

What's going on?

1 Answer 1

2
Port not opened

was the keyword in the error message: The Serial Port randomly closes from time to time. The solution is to continually force it open in draw:

Serial serial;
boolean serialInited;


void draw () {
    if (serialInited) {
        // serial is up and running
        try {
            byte b = serial.read();
            // fun with serial here...
        } catch (RuntimeException e) {
            // serial port closed :(
            serialInited = false;
        }
    } else {
        // serial port is not available. bang on it until it is.
        initSerial();
    }
}

void initSerial () {
    try {
        serial = new Serial(this, Serial.list()[0], BAUD_RATE);
        serialInited = true;
    } catch (RuntimeException e) {
        if (e.getMessage().contains("<init>")) {
            System.out.println("port in use, trying again later...");
            serialInited = false;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.