0

I have a simple push button connected to pin 2 on my Arduino. I can read this value and print it to the serial monitor without any trouble:

int pushButton = 2;

void setup() {
  Serial.begin(9600);
  pinMode(pushButton, INPUT);
}

void loop() {
  int buttonState = digitalRead(pushButton);
  Serial.println(buttonState);
  delay(1); // delay in between reads for stability
}

This prints a value of 0 when the button is not pressed, and 1 if it is.

In Processing, I want to check if the value is zero or one, and perform some conditional logic. But I can't get the equality right:

Serial myPort;
String resultString;

void setup(){
  size(640,480);
  printArray(Serial.list());
  String portName = Serial.list()[2];
  myPort = new Serial(this,portName,9600);
  myPort.bufferUntil(10);
}

void draw() {
  //
}

void serialEvent(Serial myPort){
  String inputString = myPort.readStringUntil(10); //until newline or ("\n");
  inputString = trim(inputString);
  println(inputString);
  if (inputString == "1"){ //this doesn't work, even though println will render ("1") plus the newline if button is pushed.
    println("on");
  } else {
    println("off");
  }
}

How do I set up this conditional to do one thing if the button is pushed, and another if it is not?

I've tried converting the string to an int using

inputInt = Integer.parseInt(inputString);

and then performing the check, but it didn't work.

gre_gor
  • 6,669
  • 9
  • 47
  • 52
mheavers
  • 29,530
  • 58
  • 194
  • 315

1 Answers1

0

You are using Java on host, are you?

if (inputString == "1")

Sure this fails, as these are different objects... Try this instead:

if (inputString.equals("1"))
Aconcagua
  • 24,880
  • 4
  • 34
  • 59
  • This works. Can you explain what you mean by "these are different objects" . – mheavers Jan 26 '18 at 14:50
  • 1
    String literals such as "1" in Java are objects on their own, so your comparison would be similar to something like `inputString == new String("1")`. You read inputString from some external source, it is its own string object, too, that just by accident has (or not) the same content as the string you compare it to (`"1"`). – Aconcagua Jan 27 '18 at 19:05