Problem handling text

Given the fact that im very new at arduino i think that how im handling this is not the best way, and in fact it doesnt work:

String command; 
const String MyName            = "AA";

if((Serial.available() == 2) && (IncomingData == 0) && (ConfigFlag == 0)) {
    command[0] = Serial.read();
    command[1] = Serial.read();
    if((command == MyName) && (ReadyToStream == 0) && (imready == 0)) {
      Serial.print("OK&EMPTY&RAM");
      Serial.println(memoryFree());
    }
}

If i send AA over the serial it must answer me with “OK&EMPTY&RAM” text, but i think im not doing the right statetment were command == MyName.

Thanks for any help!

A couple of things:

  1. I’m not sure you can do command[0] = Serial.read().

You probably want command.setCharAt(0, Serial.read()).

  1. Serial.read is probably going to return a signed integer, and I believe String treats its characters as unsigned bytes, so you’ll have to make sure to convert. If no character is available, Serial.read() will return -1 - so you probably want to check for that as well.

The char array that the String class wraps, when the String class constructs it, is NULL terminated. If you use the charAt() method to directly set characters, YOU must add the NULL after the last character (or, better, after each character is added). Do not forget it.

Also, what would happen if three characters snuck into the serial buffer while you were not looking. Since there are not exactly two, you would never again read any serial data. It's better to test for 2 or more characters than exactly two characters.

The == test for a match to MyName is failing because MyName is wrapping a NULL terminated array of chars, and what you are comparing it to is NOT a NULL terminated array of chars.

Thanks PaulS, can you please give me an example of what you mean? im very new and im not sure how to implement your solution

Thanks PaulS, can you please give me an example of what you mean? im very new and im not sure how to implement your solution

No, because using the String class for this purpose is a huge waste of resources. Very extensive text processing applications have been written using NULL terminated char arrays for decades before the wasteful String class was developed.

This code does not use the String call (or a bunch of unnecessary parentheses, and puts the { where they belong) but accomplishes the same desired functionality:

char *MyName = "AA";
char command[4];

if(Serial.available() == 2 && IncomingData == 0 && ConfigFlag == 0)
{
    command[0] = Serial.read();
    command[1] = Serial.read();
    command[2] = '\0';

    if(strcmp(MyName, command) == 0 && ReadyToStream == 0 && imready == 0)
    {
       Serial.print("OK&EMPTY&RAM");
       Serial.println(memoryFree());
    }
}