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?