我有一个字符串从PC通过串行到微控制器(Arduino(,例如:
"HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
通过这个函数,我发现:
String inputStringPC = "";
boolean stringCompletePC = false;
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputStringPC += inChar;
if (inChar == '$') // end marker of the string
{
stringCompletePC = true;
}
}
}
我想提取单词HDD,CPU之后的第一个数字,并在天气(即">多云"(之后获取字符串;我的想法是这样的:
int HDD = <function that does that>(Keyword HDD);
double CPU = <function that does that>(Keyword CPU);
char Weather[] = <function that does that>(Keyword Weather);
正确的功能是什么?
我研究了inputStringSerial.indexOf("HDD"(,但我仍然是一个学习者,无法正确理解它的作用,并且不知道是否有更好的功能。
我的方法产生了一些语法错误,并使我对"String inputStringSerial"(类?(和"char inputStringSerial[]"(变量?(之间的用法差异感到困惑。当我做'字符串输入字符串串行=";'PlatformIO抱怨"字符串"是未定义的。非常感谢任何帮助了解其用法。
谢谢一堆。
String类提供成员函数来搜索和复制 String 的内容。该类及其所有成员函数都记录在 Arduino 参考中: https://www.arduino.cc/reference/tr/language/variables/data-types/stringobject/
另一种表示字符列表的方式是 char 数组,令人困惑地也称为字符串或 cstring。搜索和复制 char 数组内容的函数记录在 http://www.cplusplus.com/reference/cstring/
下面是一个简单的草图,它使用 String 对象复制和打印天气字段的值。使用相同的模式(具有不同的标头和终止符值(来复制其他字段的字符串值。
获得 HDD 和 CPU 的字符串值后,您需要调用函数将这些字符串值转换为 int 和浮点值。请参阅 String 成员函数 toInt(( 和 toFloat(( 在 https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/toint/或者 char 数组函数 atoi(( 和 atof(( 在 http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoi
String inputStringPC = "HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
const char headWeather[] = "Weather: "; // the prefix of the weather value
const char dashTerminator[] = " -"; // one possible suffix of a value
const char dollarTerminator[] = " $"; // the other possible suffix of a value
void setup() {
int firstIndex; // index into inputStringPC of the first char of the value
int lastIndex; // index just past the last character of the value
Serial.begin(9600);
// find the Weather field and copy its string value.
// Use similar code to copy the values of the other fields.
// NOTE: This code contains no error checking for unexpected input values.
firstIndex = inputStringPC.indexOf(headWeather);
firstIndex += strlen(headWeather); // firstIndex is now the index of the char just past the head.
lastIndex = inputStringPC.indexOf(dollarTerminator, firstIndex);
String value = inputStringPC.substring(firstIndex, lastIndex);
Serial.print("Weather value = '");
Serial.print(value);
Serial.println("'");
}
void loop() {
// put your main code here, to run repeatedly:
}
当在Arduio Uno上运行时,此草图会产生:
Weather value = 'Cloudy [...]'