Home > Back-end >  Sending Strings from arduino to Processing
Sending Strings from arduino to Processing

Time:09-02

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);
  }
}  

CodePudding user response:

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  ; 
  } 
}  

  • Related