Unable to compare two integer values in Arduino Mega I wrote Arduino code (code is given at the end) to compare two integer values. The steps I took was:


Give input to DC motor to rotate it using serial port. Input was: G254
Then I store it in XX string and using XX.remove(0,1); I removed G from G254. XX now become 254
Then I used Serial1.println("P"); to get position of motor after rotation. I stored this value in ZZ string using String  ZZ = Serial1.readString();. ZZ will be P254.
And using XX.remove(0,1); I removed P from P254. ZZ now become 254.
Now, I convert both XX and ZZ into integer from string using  XX.toInt(); ZZ.toInt(); .
After that, I compare both values using: 



if (XX == ZZ)
{
    Serial.println("BOTH ARE EQUAL");
}
else 
{
    Serial.println("BOTH ARE NOT EQUAL");
}



But it shows BOTH ARE NOT EQUAL which is not true. I want to know where I'm making a mistake?

Code I used:

void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    Serial1.begin(9600);

    pinMode(13, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    if (Serial.available() &gt; 0)
    {
        Serial1.println(Serial.readString());

        String  XX = Serial1.readString();
        XX.remove(0,1);

        Serial1.println("P");

        String  ZZ = Serial1.readString();
        ZZ.remove(0,1);

        XX.toInt();
        ZZ.toInt();
        Serial.println(ZZ);
        Serial.println(XX);
        Serial.println(typeof(XX));

        if (XX == ZZ)
        {
            Serial.println("BOTH ARE EQUAL");
        }
        else 
        {
             Serial.println("BOTH ARE NOT EQUAL");
        }
    }    
}


Thanks.
You should use

 int x = XX.toInt()


Without the int x = part, the string is converted and the result (the integer) is not used.

Also comparing strings should be done with the strcmp function. The problem is that if you compare two strings, you compare the pointers to those strings and two strings can have equal texts but (probably) not equal addresses.