floating point - atof() returns 3 digit number into 2 digits -
i trying parse string sent arduino uno using serial communication float. want use these floats set rgb led's color. issue is, read first 2 digits. sorta. entered 100. come out 10.00. if it's 231, come out 23.00. weird thing is, if put 32.43, come out 32.4300. have no idea why this. here code:
float led1color[3]; ... (int = 0; < 3; i++) { int index = content.indexof(","); content = content.substring(index + 1); //removes additional text in front of numbers led1color[i] = atof(content.substring(0, index).c_str()); serial.println(led1color[i], 4); }
now lets sent following: "rgbled,43.61,52,231". first, rgbled removed. then, 3 values console shows me followed:
43.6100 52.0000 23.0000
obviously issue here need value 231, not 23.0000. i've never programmed in c/c++ before, there i'm missing? why 3 digit number being converted 2 digit number?
your error value of index. finds first comma correctly
int index = content.indexof(",");
but second substring uses same value of index previous find:
... content.substring(0, index).c_str() // error - index last value
so when string reduced to:
content -> "52,231"
index returns 2
then chop of comma , have
content -> "231"
the code takes 2 characters gives 23.
if change input
"rgbled,43.61,5,231"
you "2" last atof.
if change input
"rgbled,43.61,52.,231"
you "231" last atof.
the approach take of reducing string not necessary. indexof takes second parameter can specify starting point.
this code on way better solution because don't use memory keep re-assigning content string -- finds commas , processes sections:
index1 = content.indexof(","); index2 = content.indexof("," , index1+1); index3 = content.indexof("," , index2+1); led1color[0] = atof(content.substring(index1+1, index2).c_str()); led1color[1] = atof(content.substring(index2+1, index3).c_str()); led1color[2] = atof(content.substring(index3+1).c_str());
Comments
Post a Comment