4

I am very new to Arduino Programming. I am trying to identify the input string from serial monitor and printing the output to the console accordingly

Code is :

void setup() {
       Serial.begin(9600);
}

void loop() {

   while (Serial.available() > 0 ) {

     String str = Serial.readString();

     if (str.equals("send")) {
        Serial.println("identified");
     } else {
        Serial.println("unknown");
     }

   }

}

Whenever i put send string it is showing "unknown" as the output, which is wrong, and i should get "identified" as the output. Can anyone guide me here to achieve the result.

Note : I am getting output as i wanted by using readStringUntil function but the strings has a lot of "." in it, hence not useful.

KarmaCoding
  • 113
  • 1
  • 4
  • 15

3 Answers3

5

If you set your Serial Monitor's line ending to "Both NL & CR", then this code will find the word "send". It will NOT find the word "send" in this string, "ssend" or in this string, "sendd".

void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.substring(0) == "send\r\n"){
      Serial.println("identified");} 
    else{
      Serial.println("unknown");
    }
  }
}

If you want to find the string "send" in "1234send" or "send1234" or "1234send5678" then use indexOf();

void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0 ){
    String str = Serial.readString();
    if(str.indexOf("send") > -1){
      Serial.println("identified");} 
    else{
      Serial.println("unknown");
    }
  }
}
VE7JRO
  • 2,515
  • 19
  • 27
  • 29
0

There are any number of reasons the *.equals test is false. Consider case difference or extra characters introduced from the source of your communications. Even non printable characters may pose a problem and cause the test to fail.

Consider using *.substring() instead. This method will return true if the substring is found. For example:

  String stringOne = "12345 send 1234";

  // substring(index) looks for the substring from the index position to the end:
  if (stringOne.substring(0) == "send") 
  {
    Serial.println("identified");
  } 
  else
  {
    Serial.println("unknown");
  } 

...should always return "identified" because the characters 's', 'e', 'n' and 'd' are found in the correct sequence within the string stringOne.

st2000
  • 7,513
  • 2
  • 13
  • 19
0
void setup() {
       Serial.begin(9600);
}

void loop() {
   char inChar[5];

   if(Serial.available() > 0 )
   {
     for (int i=0; i<5; i++)
     {
      inChar[i] = Serial.read();
      delay(10);
     }

     if (inChar[0] == 's' && inChar[1] == 'e' \
                          && inChar[2] == 'n' \
                          && inChar[3] == 'd')
         {
          Serial.println("identified");
         }

     else
     {
       Serial.println("unknown");
     }
  }
}
MatsK
  • 1,366
  • 1
  • 11
  • 24