将字符串转换为浮点数在处理中发生 NaN 错误 [英] Convert string to float occurs NaN error in Processing
问题描述
我在Processing中遇到一个问题,当我将值(字符串)转换为浮点数时,第一个值是好的,但其余的都是NaN
.我找不到解决这个问题的方法.我打印字符串值进行测试.这是正确的,但在我将其转换为浮点数之后.它将是 NaN
.
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:该值来自串行,我将我的 Arduino 与 Proceesing 连接起来.
ps: the value is from the serial, i connected my Arduino with Proceesing.
以下是代码的一部分
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);
}
}
以下是结果
以下是arduino代码
sum = sqrt(Xg*Xg + Yg*Yg + Zg * Zg);
sum *= 10;
sum = (map(sum, 0, 1024, 0, 5000)/10.0);
Serial.println(sum);
delay(100);
推荐答案
我发现我的问题出在 Arduino 代码中,所以我改变了从 Arduino 发送数据的方式.我使用 println()
发送数据.这就是导致 NaN
的重点.我在谷歌上搜索,然后我测试了不同的方法来改变发送方式,直到我找到这个链接:http://www.varesano.net/blog/fabio/sending-float-variables-over-serial-without-loss-precision-arduino 和处理
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
感谢 fabio 的博客,他的博客介绍了解决此问题的好方法.如果你有同样的问题,也许你可以通过这个解决.
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.
这篇关于将字符串转换为浮点数在处理中发生 NaN 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!