Multiple Values from Processing to Arduino through Serial Port

I have managed to send one value from processing to arduino. (which maps mouseX and lights the respective LED on an LED strip of Neopixels) I went through a lot of forums and tried to send Mouse Position(2 values ) from processing to arduino … By trying to separate the numbers using substring and toInt … But then the program doesn’t seem to be working.
can anyone share an simple example that sends and receives X and Y values, or multiple values.

Hi Cai,

It can be quite tricky to communicate with an arduino. I spent 2 days figuring out how to do it for my project: A universal ambilight

I adapted the basic Serial example form processing. The idea stays the same: when the mouse is over the rectangle then then an LED connected to the pin number 4 light up.

The processing code:

import processing.serial.*;

Serial myPort;

void setup() 
{
  size(300, 300);
  myPort = new Serial(this, Serial.list()[0], 9600);
  delay(5000);
}

void draw() {
  background(20);
  
  myPort.write(mouseX + ";" + mouseY + ";");

  if (mouseOverRect()) {
    fill(220, 20, 20);
  } else {
    fill(200);
  }
  rect(100, 100, 100, 100);
}

boolean mouseOverRect() { // Test if mouse is over square
  return ((mouseX >= 100) && (mouseX <= 200) && (mouseY >= 100) && (mouseY <= 200));
}

The arduino code:

const long BAUD_RATE = 9600;
int x, y;

void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  newData = false;
  x = 0;
  y = 0;
}

void loop() {
  receiveData();
  
  if (x >= 100 && x <= 200 && y >= 100 && y <= 200) {
    digitalWrite(4, HIGH);
  } else {
    digitalWrite(4, LOW);
  }
}

void receiveData() {
  if (Serial.available() > 0) {
    x = Serial.parseInt();
    y = Serial.parseInt();
    Serial.read();
  }
}

Two things are worth noticing:

  • The delay(5000) is used to let the time to the arduino mode to correctly make the connection with the computer.
  • Be careful at the baud rate, it can be the reason why you can’t read some data. In my project, I had to set the baud rate to 500000 to make it works.
1 Like

I got that … thank you , made my day …
I was wondering , as to how could i replicate a processing sketch on Arduino … in a X, Y grid I have managed to find the index number of the LED and corresponding to (mapped)mouseX and mouseY .
for example in an grid of 3*3
how could I send values such that I can draw an diagonal line ?

0 – 0 – 1
0 – 1 – 0
1 – 0 – 0

I can make that arduino … But i want to use interactivity of processing and display it on my arduino XY grid made out of neo pixels …