问题
I meet a problem in the Processing, and when i convert the value(string) into float, the first value is good, but the rests are all NaN
. I could not find a way to solve this. And i print the string value for test. And it is correct, but after i convert it into float. It will be NaN
.
ps: the value is from the serial, i connected my Arduino with Proceesing.
following is a part of codes
while(myport.available() > 0)
{
myString = myport.readString(); //read the string from serial
num = float(myString); // convert the string into float
print(num); // print the num(float), but the first
// value is good, rests are all `NaN` .
//print(myString); // print string, all the values are good
print(' ');
if(myString != null)
{
//num = float(myString);
storeData(myString);
//println(myString);
//print(data[i - 1]);
//println(' ');
delay(1000);
}
}
following is the result
conversion finshed:
not convert, only print string value
following is arduino code
sum = sqrt(Xg*Xg + Yg*Yg + Zg * Zg);
sum *= 10;
sum = (map(sum, 0, 1024, 0, 5000)/10.0);
Serial.println(sum);
delay(100);
回答1:
I think that the problem is not inside Arduino but inside the Processing code.
I was looking a lot and I note that there is an error that can most likely solve your problem.
You used val = myport.readString();
instead of val = myport.readStringUntil('\n');
.
The differences are few, but in your case would be substantial. Take a look at ReadString function and ReadStringUntil function.
Anyway, it is also suggested by the sparkFun tutorial.
P.S. Of course, in your Arduino code, you have to use (well, like you were doing) Serial.println(sum);
instead of Serial.print(sum)
because, in the last case, that would not send to processing nothing before a line feed has been sended.
回答2:
I find my problem is inside the Arduino code, so i changed the way to send the data from Arduino. I used the println()
to send the data. And that's the point lead to NaN
. I serached on google, and then i tested different ways to change the way to send until i finded this link:http://www.varesano.net/blog/fabio/sending-float-variables-over-serial-without-loss-precision-arduino-and-processing
And thanks fabio's blog, his blog's introudces a good way to solve this problem. If you have the same trouble, maybe you can fixed by this.
来源:https://stackoverflow.com/questions/33054809/convert-string-to-float-occurs-nan-error-in-processing