# Not sure how to handle this incoming string

I am reading some data from a 3D printer with an Arduino Pro Mini and this is an example of the incoming string,

X:0.00Y:0.00Z:450.20E:0.00

What I want to end up with is 4 separate variables of X, Y, Z, and E like this

X = 0.00 Y = 0.00 Z = 450.20 E = 0.00

I can read strings, and I can convert them to numbers but how do I handle the Decimal point and I'm not sure the best way to break the data up into the 4 variables.

Would it be best to simply take the string from the buffer and then use Substring to pull out the 4 variables? Any example would be great!

Thanks!

You could find the start index of each letter ( X,Y,Z,E ) and then use atof at the ( start + 1 ) locations to get each float value.

http://www.cplusplus.com/reference/cstdlib/atof/: atof: The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see here), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

This seemed to work. With a little tidy up, it should do.

``````int InStr( char c, char *str ){

char *cursor = str;
while( *cursor ){
if( *cursor == c ) return cursor - str;
++cursor;
}
return -1;
}

void setup()
{
Serial.begin( 9600 );

char *str = "X:0.00Y:0.00Z:450.20E:0.00";
float f_X = atof( str + InStr( 'X', str ) + 2 );
float f_Y = atof( str + InStr( 'Y', str ) + 2 );
float f_Z = atof( str + InStr( 'Z', str ) + 2 );
float f_E = atof( str + InStr( 'E', str ) + 2 );

Serial.print( "X: " );
Serial.println( f_X );
Serial.print( "Y: " );
Serial.println( f_Y );
Serial.print( "Z: " );
Serial.println( f_Z );
Serial.print( "E: " );
Serial.println( f_E );
}
``````

Output:

X: 0.00 Y: 0.00 Z: 450.20 E: 0.00

Awesome, Thanks!

Was not aware of the AtoF function. That helps a lot.