Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check string to be 1, 0 else print string

I have an arduino connected to my computer (COM9) and I have 3 python scripts. The first sends a "1" over serial. The second sends a "0" over serial. The third sends a word that you give it.

ser.write("1")

Then on my arduino I have some code. If the python script 1 is launched it would turn on a led. If the 2 second script is launched it would turn off a led. If python script 3 is launched it would print the word to an lcd.

All hardware is configured correctly. The problem is that when I run script 1 not only the led would turn on but there will also be a 1 on the lcd. The other 2 scripts work as expected.

This is a part of the code on my arduino.

 if (Serial.available())
  {
     wordoftheday = Serial.readString();
     if (wordoftheday == "1"){email = true;}
     if (wordoftheday == "0"){email = false;}
     else { 
      lcd.clear();
      lcd.print(wordoftheday);
      }
  }

  if (email == true){digitalWrite(9, HIGH);}
  if (email == false){digitalWrite(9, LOW);}
like image 240
Tristan Avatar asked Mar 14 '23 08:03

Tristan


2 Answers

You can't compare strings using ==

if (wordoftheday == "1"){email = true;}

should be

if (strcmp(wordoftheday, "1") == 0){email = true;}

And (as pointed out by @chux), it seems that you forget an else:

 if (strcmp(wordoftheday, "1") == 0)
     email = true;
 else
 if (strcmp(wordoftheday, "0") == 0)
     email = false;
 else { 
     lcd.clear();
     lcd.print(wordoftheday);
 }
like image 62
David Ranieri Avatar answered Mar 23 '23 23:03

David Ranieri


Besides the previous answer about the compare, you are setting up the ifs incorrectly. When the first if is true, you fall into the else of the second if.

if (Serial.available())
{
    wordoftheday = Serial.readString();
    if (strcmp(wordoftheday, "1")) {email = true;}
    else if ((strcmp(wordoftheday, "0")){email = false;}
    else { 
        // Enters here only if both of the above are false
        lcd.clear();
        lcd.print(wordoftheday);
    }
}
like image 25
sabbahillel Avatar answered Mar 23 '23 23:03

sabbahillel