0

我正在尝试将使用串行通信发送到我的 arduino uno 的字符串解析为浮点数。我想使用这些浮点数来设置 RGB LED 的颜色。我的问题是,它只会读取前 2 位数字。排序。假设我输入了 100。它只会出现到 10.00。如果是 231,它将出现在 23.00。奇怪的是,如果我输入 32.43,它会出现 32.4300。我不知道它为什么这样做。这是我的代码:

float led1Color[3];

...

for (int i = 0; i < 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);
}

现在假设我发送了以下内容:“RGBLED,43.61,52,231”。首先,移除 RGBLED。然后,控制台显示的 3 个值如下:

43.6100 52.0000 23.0000

显然这里的问题是我需要值 231,而不是 23.0000。我以前从未真正用 C/C++ 编程过,所以有什么我遗漏的吗?为什么三位数会变成二位数?

4

1 回答 1

1

您的错误是索引的值。这会正确找到第一个逗号

int index = content.indexOf(",");

但是第二个子字符串使用与上一个查找相同的 index 值:

... content.substring(0, index).c_str()  // ERROR - index is the last value

所以当字符串减少到:

content -> "52,231"

索引返回2

然后你砍到逗号并有

content -> "231"

代码从给你 23 的代码中取 2 个字符。

如果您将输入更改为

"RGBLED,43.61,5,231"

最后一个 atof 会得到“2”。

如果您将输入更改为

"RGBLED,43.61,52.,231"

最后一个 atof 会得到“231”。

您减少字符串的方法是不必要的。indexOf 采用可以指定起点的第二个参数。

这段代码正在寻找更好的解决方案,因为您不使用内存来不断重新分配内容字符串——它只是找到逗号并处理这些部分:

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());
于 2014-08-17T23:35:20.343 回答