Sending Strings from Arduino to Processing

What’s wrong with an array:
https://stackoverflow.com/questions/73545324/sending-strings-from-arduino-to-processing

You’re sending two separate strings, each with a line feed terminator. Processing can’t read both of them at once and magically split them into two variables that only you know about. Processing will read each one as they are sent. First pass will fill index[0] of the array. Second pass will fill index[1]. You could send both messages as one long string and then parse them into s1 and s2 by using some terminator after message 1, but that is more complicated than what you are doing. The way it is Processing is only going to report two separate readings because that’s what you told it to do: read up to the first line feed (Arduino ‘println’ puts a line feed at the end of the string) and then read up to the second line feed. With the array concept what comes in first is s[0] and what comes in second is s[1]. If you must use the s1 and s2 variables then s1 = s[0] and s2 = s[1]. Perhaps the following will help you see what is going on:

import processing.serial.*;

Serial myPort;
String[] s; // Array to hold two strings.
int counter = 0;

void setup() { 
  myPort = new Serial(this, "COM3", 9600);
  s = new String[2];
  println("===========");
}

void draw() { 
String str = myPort.readStringUntil('\n');
  if(str != null) {
    s[counter] = str;  
    printArray(s);
    println("===== end of read",counter+1 + " =======");
    counter++; 
  } 
  
} 
1 Like