Hi, I’m having problems with an array being updated inside SerialEvent handler.
This is the case:
- I’m using grafica library
- I get some data from an Arduino through the serial port. I handle this through a SerialEvent handler.
- I update a GPointsArray inside the SerialEvent handler.
- In the draw() loop I draw the incoming data.
The problem is I keep getting “IndexOutOfBoundsException” when calling the draw method of the plot, and the error doesn’t make sense. For example: “IndexOutOfBoundsException: Index: 29, Size: 62”. It’s clear that the index is in bound.
The problem seems to be that the SerialEvent handler and the draw() function are both trying to access the array at the same time. Any suggestion?
This is a simplified code to reproduce the error:
import processing.serial.*;
import grafica.*;
Serial port;
GPlot plotPos;
GPointsArray ws;
int wsN = 100;
void setup() {
size( 800, 600 );
ws = new GPointsArray(wsN); //Create th points array
plotPos = new GPlot(this); //Create a new plot
plotPos.setPoints(ws);
plotPos.setPos(20, 20);
plotPos.setDim(width *0.82, height*0.6);
if ( openComm() == 1 ) {
exit();
}
}
void draw() {
plotPos.defaultDraw(); //Draw everything
}
void serialEvent(Serial port) {
String inString = port.readString();
if ( ws.getNPoints() >= wsN )
ws.remove(0);
ws.add(mouseY, mouseX); //Add some random data to the array.
plotPos.setPoints(ws);
inString = "";
}
int openComm() {
String[] serialPorts = Serial.list(); //Get the list of tty interfaces
for ( int i=0; i<serialPorts.length; i++) { //Search for ttyACM*
if ( serialPorts[i].contains("ttyACM") || serialPorts[i].contains("ttyUSB0") || serialPorts[i].contains("COM") ) { //If found, try to open port.
println(serialPorts[i]);
try {
port = new Serial(this, serialPorts[i], 115200);
port.bufferUntil(10);
}
catch(Exception e) {
return 1;
}
}
}
if (port != null)
return 0;
else
return 1;
}