Having trouble serial communicating with arduino

I'm writing my first processing code, but I've worked with arduino a lot before and I'm not a total newbie in coding. I'm trying to have my arduino send some strings over serial and have my processing code play a file, depending on what string comes.

import processing.serial.*;

import ddf.minim.*;

Minim minim;
AudioPlayer song;

  Serial myPort;  
  String val;     
  String first = "option1";
  String second = "option2";
  String third = "option3";

void setup()
{

  String portName = Serial.list()[5]; 
  myPort = new Serial(this, portName, 9600); 
}

void draw()
{
    size(100, 100);
    minim = new Minim(this);  

    if ( myPort.available() > 0) {  
    val = myPort.readStringUntil('\n'); 
    } 

   println(val);
  if(val == first){
      song = minim.loadFile("Voice1.mp3");
      song.play();
      println("worked");
    }
  else if(val == second){
      song = minim.loadFile("Voice2.mp3");
      song.play();
       println("worked");
    }
  else if(val == third){
      song = minim.loadFile("Voice3.mp3");
      song.play();
       println("worked");
    }   

background(0);
}

The problem itself probably doesn't have to do with the serial communication. The thing is that the if/else if statements are never true. I can see the "val" printed on the console and I can see it's equal to either "first", "second", or "third" but the statements are never true. Thanks

Answers

  • Please, read carefully the String reference, talking about comparison with ==

    That's a very common error...

  • I changed it to .equals() and still have the same problem.

  • edited September 2014

    In addition to .equals(), you should use trim():

    if (trim(val).equals(first)) {
      println("worked");
    }
    

    AFAIK, the serial buffer gives you extra whitespace characters. If you just print out the values, you won't necessarily detect the presence of these characters, especially if they are after your data...

Sign In or Register to comment.