HELP strcmp in IF statement is always false

Hello There ,

I implementing code example 2 of this link Example 2

and I modified those code to study strcmp like bellow :

// Example 2 - Receive with an end-marker

const byte numChars = 32;
char receivedChars[numChars];   // an array to store the received data

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithEndMarker();
    showNewData();
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;
   
    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        if(strcmp(receivedChars, "123") == 0){
          Serial.println("Your chois is Right");
          
        }
        else {
          Serial.println("Your chois not good");
        }
        
        Serial.println(receivedChars);
        newData = false;
    }
}

but the result is always FALSE ("Your chois not good") Please See Attachment

I do not understand how to compare using strcmp in the right ways
Please HELP what is wrong in my code
Thanks

you serial console sends both CR and NL (LF).


The new line will trigger the end of the input string but you still captured the CR and it's in the message.
=> set the console to send only NL, or compare with "123\r"

PS: you could also ignore '\r' if you receive it (don't add it to the message you build)

if (rc != endMarker) {
  if (rc != '\r') { // ignore '\r'
    receivedChars[ndx] = rc;
    ndx++;
    if (ndx >= numChars) {
      ndx = numChars - 1;
    }
  }
} else ...

Welcome

Or you could use strncmp to compare only the first n characters of the string

if(strncmp(receivedChars, "123", strlen("123")) == 0)

J-M-L:
you serial console sends both CR and NL (LF).


The new line will trigger the end of the input string but you still captured the CR and it's in the message.
=> set the console to send only NL, or compare with "123\r"

PS: you could also ignore '\r' if you receive it (don't add it to the message you build)

if (rc != endMarker) {

if (rc != '\r') { // ignore '\r'
   receivedChars[ndx] = rc;
   ndx++;
   if (ndx >= numChars) {
     ndx = numChars - 1;
   }
 }
} else ...

thanks for your help , I never counted or thought about this.

guix:
Welcome

Or you could use strncmp to compare only the first n characters of the string

if(strncmp(receivedChars, "123", strlen("123")) == 0)

ok I will try both , thanks

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