String char does not match in IF...ELSE confront

I have this piece of code:

    sprintf(buf, "Cmd: %s", msgIn);
    Serial.println(buf);

    if (msgIn == "STA") {
      sprintf(buf, "STATUS: B=%d - R=%d0", battery, records);
    } else if (msgIn == "RED") {
      sprintf(buf, "T=%s: P=%d0: HR=%d0: D=%d: E=&s", sTemp, press, hum, dist, sEner);
    } else {
      sprintf(buf, "Unrecongnized command");
    }

Now, 'msgIn' is defined as char msgIn[MAX_MESSAGE_LEN]; //41 bytes.
I checked the lenght which correctly is of 3 bytes and it is printed out on the monitor as STA or RED.
The above IF...ELSE never match a correct string; it always falls to 'unrecognized'.
For sure I'm missing something in the sintax

you should use strcmp() for this try of c-string comparision.

so from your snippet, something like this should work:

void setup() {
    char msgIn[41] = "RED"; //"STA" , "CMD"
    char buf[128];
    
    //dummy input values
    int battery=0, records=0, press=0, hum=0, dist=0;
    char *sTemp="sTemp", *sEner = "sEner";
    
    Serial.begin(115200);
    sprintf(buf, "Cmd: %s", msgIn);
    Serial.println(buf);

    if (strcmp(msgIn, "STA")==0) {
      sprintf(buf, "STATUS: B=%d - R=%d", battery, records);
    } 
    else if (strcmp(msgIn, "RED")==0) {
      sprintf(buf, "T=%s: P=%d: HR=%d: D=%d: E=%s", sTemp, press, hum, dist, sEner);
    } 
    else {
      sprintf(buf, "Unrecongnized command");
    }

    Serial.println(buf);

}

void loop() {
  // put your main code here, to run repeatedly:

}

hope that helps....

Yes, thanks, this is another quirk with the pseudo-strings that is difficult for me to assimilate...too many years of simple msgIn="STA" :wink:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.