Hello,
I am having some problems spliting the folowing string in diferent variables(value1,value2, value3, value4;):
uint8_t* buf = "SENDER_1,20.5,65.4,20";
String value1;
float value2, value3, value4;
sscanf(buf, "%s,%f,%f,%f", &value1, &value2, &value3, &value4);
Serial.println(value1);
Serial.println(value2);
Serial.println(value3);
Serial.println(value4);
when i compile de code give me an error : "error: invalid conversion from 'uint8_t* {aka unsigned char*}' to 'const char*' [-fpermissive]"
I was wondering if any one could help me formulate a function to achieve my goal? Thankyou =)
You can use strtok() to parse a comma (or other character) separated character string:
#define MAX_VALS 4
char buf[] =
"SENDER_1,20.5,65.4,20";
char
*token;
uint8_t
idx;
char
*pszValues[MAX_VALS];
void setup()
{
Serial.begin(115200);
Serial.println( "Starting..." );
idx = 0;
token = strtok( buf, "," );
while( token != NULL )
{
//Serial.println( token );
if( idx < MAX_VALS )
pszValues[idx++] = token;
token = strtok( NULL, "," );
}//while
Serial.print( "Value 0: "); Serial.println( pszValues[0] );
float value2 = atof( pszValues[1] );
Serial.print( "Value 1: "); Serial.println( value2, 1 );
float value3 = atof( pszValues[2] );
Serial.print( "Value 2: "); Serial.println( value3, 1 );
float value4 = atof( pszValues[3] );
Serial.print( "Value 3: "); Serial.println( value4, 1 );
}//setup
void loop()
{
}//loop
I'd avoid the use of capital-S Strings in Arduino projects due to the potential for memory usage issues.
Once strtok() separates the pieces use atof() on the float strings to convert them to float numbers, if necessary.
gcjr
4
there are two problems
- sscanf() is designed to be used with c strings not String. define char value1 [20]
char value1 [20];
- c++ wants string constants to be defined as "const char"
const char * buf = "SENDER_1,20.5,65.4,20";
6v6gt
5
The default Arduino configuration does not support floating point operations for, amongst others, sscanf():
Thank you very much...... its working. 