Serial Communication Issues--Arduino

Hi! I’m trying to re-write a processing program that was designed for v2 to work with v3. In short, I’m trying to take data from an Arduino and plot, calculations, etc in Processing. It wasn’t clear what about the program was incompatible with v3, so I figured I’d start from scratch. It seems like the problem(or at least the first problem) has to do with the serial communication from the Arduino. For troubleshooting sake, I have the Arduino printing “130” as a ASCII-encoded decimal with a newline character at the end to the Serial port.

On the processing side, I create a window, and want the value coming from the serial port to be shown as text in the center of the screen. However, the line containing “text(inString, width/2,height/2);” gets highlighted and the console indicates a “NullPointerException” every time I run it.

It’s worth noting that The program works fine if I have it print the value straight to the console.(If I comment out the “text” code) Any ideas?

import processing.serial.*;
String SerialIn;

Serial myPort;

void setup(){
  
  //Setup Window
  size(1200,300);
  background(255,255,255);
  stroke(0,0,0);
  
  //Setup Serial
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
  
}

void draw() {
  background(255,255,255);
  SerialIn = myPort.readStringUntil('\n');
  text(SerialIn, width/2,height/2);
  fill(0,0,0);
 // println(SerialIn);
}

Thank you!

1 Like

Update: I realized that I didn’t pass the serial port to the draw method. Pointer issue is gone, but now the value from the Arduino won’t print to the screen or console.

if “myPort.readStringUntil(’\n’);” is unable to find a ‘\n’ from the serial port it will return null.
It couldn’t hurt to add this before the read:

if (myPort.available() >= some_expected_string_length)
...

With that, you will also want to initialize SerialIn to something other than null.

Could you also post the arduino side code?

1 Like

@hbara Please check previous examples working with arduino units. This next is a gold example that works in many applications: https://forum.processing.org/two/discussion/16618/processing-with-arduino-void-serialevent#Item_5

You need to understand that Processing receives data at a rate that could be different to your draw()'s frame rate. Therefore, one way to do this is to retrieve data only when is available or to trigger data processing as soon as it arrives.

Kf

1 Like