0

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?

Regards

Arduino Code

void setup() {
  Serial.begin(9600);
  delay(1000);
  Serial.println("1.first message");
  Serial.println("2.second message"); 
  delay(100);
}
void loop() {

}

Processing Code

import processing.serial.*;
Serial myPort;
void setup() {
  myPort=new Serial(this, "COM3", 9600);
}

void draw() {
  String s1=myPort.readStringUntil('\n');
  String s2=myPort.readStringUntil('\n');

// printing variables
  if(s1!=null){
  print("s1:",s1);
  }
  if(s2!=null){
   println("s2:",s2);
  }
}  
0

1 Answer 1

0

The following works on my Mac system. The incoming strings are placed in a string array as they arrive. The string at index[0] then becomes s1 and the string at index[1] is s2. I also added a delay(100); between the two strings on the Arduino side, but this may not be necessary; you can try it both ways.

import processing.serial.*;

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

void setup() { 
  printArray(Serial.list()); // List of serial ports
  // Enter appropriate number for your system
  myPort = new Serial(this, Serial.list()[2], 9600);
  s = new String[2];
  println("===========");
}

void draw() { 
String str = myPort.readStringUntil('\n');
  if(str != null) {
    s[counter] = str;    
    if(counter == 0){
      println("s1 = ",s[0]);
    } else {
      println("s2 = ",s[1]);
    }
    counter++; 
  } 
}  

Sign up to request clarification or add additional context in comments.

3 Comments

thanks alot! this alternative way may help. it seems that for some reason the method readStringUntil() can only be called once.
It's actually called more than once but your data is only sent once and the strings are not sent simultaneously (there is a lag between them). It's coded to report only when there is a string available. On the first pass s1 has a value and s2 is null. On the second pass it will pick up s2 (after Arduino has sent it). If you found the code helpful could you please check it as the answer.
thanks, you are right. The draw function will pick up both strings in one loop if I simply add a delay to my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.