新的 SafeString Arduino 库(可通过库管理器获得)提供了一个 stoken() 方法和一个 toLong() 方法来处理这种情况并避免 String 类的堆碎片问题。
有关详细教程,请参见
https://www.forward.com.au/pfod/ArduinoProgramming/SafeString/index.html
#include "SafeString.h"
void setup() {
Serial.begin(9600);
createSafeString(appCmd, 50); // large enough for the largest cmd
createSafeString(token1, 10);
createSafeString(token2, 10);
createSafeString(token3, 10);
long r;
long g;
long b;
appCmd = "1,20a,100";
token1.clear();token2.clear();token3.clear(); // clear any old data
size_t nextIdx = 0;
nextIdx = appCmd.stoken(token1, nextIdx, ",");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token2, nextIdx, ",");
nextIdx++; //step over delimiter
nextIdx = appCmd.stoken(token3, nextIdx, ",");
nextIdx++; //step over delimiter
// now parse the numbers
bool have3ValidNumbers = true;
if (!token1.toLong(r)) {
have3ValidNumbers = false;
Serial.print("Red number invalid:");Serial.println(token1);
}
if (!token2.toLong(g)) {
have3ValidNumbers = false;
Serial.print("Green number invalid:");Serial.println(token2);
}
if (!token3.toLong(b)) {
have3ValidNumbers = false;
Serial.print("Blue number invalid:");Serial.println(token3);
}
if (have3ValidNumbers) {
Serial.print("The values are ");
Serial.print(" r:");Serial.print(r);
Serial.print(" g:");Serial.print(g);
Serial.print(" b:");Serial.print(b);
Serial.println();
}
}
void loop() {
}
此输入“1,20a,100”的输出是
绿色数字无效:20a
'标准' toInt() 方法将返回 1 20 100 作为结果。
对于像“1,a,50”这样的输入,“标准”toInt() 方法将返回 1 0 100
SafeString toLong() 方法在尝试将字符串转换为整数时会进行更多错误检查。
您还应该添加对 <0 和 >255 的检查,以确保输入是有效范围