Search code examples
cstringarduinocomparisonascii

Concatenate ASCII to String for comparaison


I'm using Arduino with Serial BUS and trying to make it interact according to the word ASCII that I send on the bus. I went through many many websites and found a lot of solutions without be able to trully find what I'm looking for.

Exemple if I send "123":

char requestBuffer[10];    
void loop(){
   if (Serial.available() > 0){
       int bytesRead = Serial.readBytesUntil('\n', requestBuffer, 10);

       char mott[3];
       mott[0] = (int)requestBuffer[0];
       mott[1] = (int)requestBuffer[1];
       mott[2] = (int)requestBuffer[2];

       Serial.println(mott); // it does print 123
       if ( mott == 123 ){   // doesn't works
           blablabla.
       }
   } 
}

I don't really know how to properly store in a variable what is typed in order to compare it. I'm not super friendly with C so maybe there are some ways to do that, that I didn't understand yet.


Solution

  • char mott[3]; needs to be char mott[4] = {0}; else you don't have a NUL terminator in your println call. Currently the behaviour of your program is undefined. Your println currently works because of an unfortunate accident.

    Once you have your mott array, use int n = atoi(mott); to convert the char string to an int. Here the array mott decays to a char* pointer, which is an acceptable type for atoi.

    (The expression mott == 123 is comparing the char* pointer to the first element of the mott array to 123, which it almost certainly isn't.)