How use sscanf with a String

I am using some 3rd party library which comes with a method which passes a String as argument.

I cannot get sscanf() to work with this String. I tried copying the content of the String to a char array[], but no luck...

This example code is self explanetory.

// some QOL macros to print texts and numbers n such
#define printNumber( txt, x )   Serial.print( txt ) ; Serial.print( x ) ;
#define printNumber_( txt, x )  Serial.print( txt ) ; Serial.print( x ) ;Serial.write(' ');
#define printNumberln( txt, x ) Serial.print( txt ) ; Serial.println( x ) ;


void incommingMessage( uint32_t from, String msg ) // it's a String -_-"
{
    uint8_t state ;
    uint8_t tokenID ;

    char *ptr1;
    char *ptr2;
      
    char char_array[32]; // temp char array to be used with sscanf()

    // char_array = msg ; // DOES NOT WORK
    
    //ptr1 = & msg[0] ;
    //ptr2 = & char_array[0] ;

    //for( int i = 0 ; i < 5 ; i ++ ) // 5 characters suffice
    //{
    //  *ptr2++ = *ptr1++ ; // DOES NOT WORK
    //}

    //strcpy(char_array, msg); // DOES NOT WORK

    //sscanf( msg, "%d,%d", &tokenID, &state ) ; // DOES NOT WORK

    // WHAT DOES WORK?
    
    sscanf( char_array, "%d,%d", &tokenID, &state ) ;

    Serial.println(char_array) ;
    printNumber_("tokenID: ", tokenID ) ;
    printNumberln("state: ", state ) ; 
    printNumberln("from: ", from) ;
}

void setup()
{
   Serial.begin( 115200 ) ;
   incommingMessage( 123, "1,5" ) ;
   delay(300);
    incommingMessage( 123, "2,2" ) ;
    delay(300);
    incommingMessage( 123, "0,0" ) ;
    delay(300) ;
    incommingMessage( 123, "1,1" ) ;
    delay(300) ;
    incommingMessage( 123, "3,4" ) ;
    delay(300) ;
    incommingMessage( 123, "9,5" ) ;

}

void loop()
{
}

What does work?

regards,

Bas

use

sscanf( msg.c_str(), "%d,%d", &tokenID, &state ) ;

I found the problem.. I stepped in it earlier.. %d wants 16 bit variables, not 8 bits...

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