1
votes

Basically, I'm trying to use the data received by a Force Sensing Resistor to change the color of the background of a processing sketch. The problem I'm running into is that the Arduino serial port runs fine/quickly, but the Processing serial port is incredibly slow/has a really delayed response.

I've tried adding a delay in the Arduino loop, but when I add that line of code I receive a NullPointerException error, even though I have a default value for the background_color variable. I also tried using a myPort.clear() function at the end of the loop, and although I didn't receive an error it messed with the color and gave a flickering effect because the values were being cleared so often.

This is the arduino code:

int A = A0;
int fsrreadingA;

int motorMap = 255; 
int forceMap = 300;
int scalar = 4;

void setup() {
  pinMode(A, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  fsrreadingA = analogRead(A) * scalar;
  int valA = map(fsrreadingA, 0, forceMap, 0, motorMap);

  analogWrite(3, valA);
  Serial.println(valA);

  delay(100);
}

This is the processing code:

import processing.serial.*;

Serial myPort;  
float background_color = 0;

void setup() {
  size(500,500);
  colorMode(HSB, 255);

  println("Available serial ports:");
  println(Serial.list());

  String portName = Serial.list()[1];
  myPort = new Serial(this, portName, 9600);
}

void draw() {  
  if (myPort.available() > 0) {
    background_color = float(myPort.readStringUntil('\n'));        
    println(background_color);

  }

  background(background_color,150,100);
}

What I expect is that the background color changes as the user presses on the FSR more/less. It should change from a brown color to a purple/pink color. I'm not sure what to do/how to fix the NullPointerException error. Is there a different way I should go about this?

1

1 Answers

0
votes

Your Arduino seems to still be sending data far too fast for Processing to react.

On the Processing side you have a FIFO buffer so if you're not able to keep up reading from the RX buffer you'll start to drop the data received most recently.

You can try sending data from the Arduino only when a certain change has occurred on the ADC readings and/or clear the buffer on Processing after reading:

myPort.clear() 

If neither of these approaches solves your issue you might also be running a buggy version of Processing, you might want to update it.