We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I'm getting a "nullPointerException" error in Processing when reading the serial port with data from an Arduino. It successfully pulls the content of the serial port but then throws the error after a few times. When the error occurs processing highlights the line in bold below(val = new....) The first chunk of code is from Processing. I've included the arduino code below as well. Best answer gets a custom poem(subject of their choice).
What's the goal? - I'm taking readings from the photocell via arduino and passing the values to processing to display. <
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val; // Data received from the serial port
void setup()
{
String portName = Serial.list()[7]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if ( myPort.available() > 0)
{ // If data is available,
** val = new String(myPort.readBytesUntil('\n'));**
println(val); //print it out in the console
}
}
/* Photocell simple testing sketch.
Connect one end of the photocell to 5V, the other end to Analog 0.
Then connect one end of a 10K resistor from Analog 0 to ground
int photocellPin = 0; // the cell and 10K pulldown are connected to a0
int photocellReading; // the analog reading from the sensor divider
int horn = 12;
int marks = 0;
int total = 0;
void setup(void) {
// We'll send debugging information via the Serial monitor
Serial.begin(9600);
pinMode(horn, OUTPUT);
}
void loop(void) {
photocellReading = analogRead(photocellPin);
//writes values that the photocell is reading
//Serial.print("Analog reading = ");
// Serial.println(photocellReading); // the raw analog reading
if(photocellReading < 80){
digitalWrite(horn, HIGH);
marks++;
//Serial.println(marks);
}else{
digitalWrite(horn, LOW);
total = total+marks;
marks = 0;
}
Serial.println(total);
delay(100);
}
Answers
There was a similar question here: http://forum.processing.org/two/discussion/2307/serial-with-arduino/p1 The problem was that when creating a new String, the output from readBytesUntil() temporarily becomes
null
. Try replacing line 21 with this:if(val != null) println(val);
@colouredmirroball - I tried that but still get the error. In the Processing code above it's line 20 that gets highlighted by Processing when the error occurs. Thoughts?
I've restarted the sketch several times and sometimes it runs uninterrupted and the other times it throws the nullPoint error.
@colouredmirrorball I've added a delay of 2 seconds at the beginning of the program and now it doesn't throw the error. Why do you think that is?
I don't know for sure. Maybe myPort takes some time to initiate? But it should check against that...