I want to get Processing to read Strings from Arduino.
I send two Strings massages from the arduino and I want to store them in two different variables on Processing.
I tried to do it, but the two Strings are passed to the first variable and the second variable remains empty. I don’t understand why this is the case. Can someone help?
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++;
}
}
thank you @svan. I posted first here but my account was blocked and the post was hidden until now. So I posted the same question on Stack overflow. It is now clear for me
Good luck on your project. I understand the double posts now. This is a good forum and I’m sorry that your initial question was not posted right away. Thank you for your participation.
The Arduino sketch is sending your text followed by Carriage Return (CR) and Line Feed (LF). You can see the exact characters by putting this in place of your draw() code.
int inp;
while (myPort.available() > 0)
{
inp = myPort.read();
print(String.format("%02X ",inp));
}
The “0D 0A” is CRLF. In Processing that CRLF will be on the end of your s1, s2 vars. This might cause confusion later. I prefer to have only LF with this Ard line.
Serial.print("1.first massage\n");
In Processing, where you print s1, it looks like you are using println because of the CRLF contained in s1. (s2 the same.)