use*_*310 10 c string parsing arduino delimiter
Arduino(C语言)解析带分隔符的字符串(通过串行接口输入)
在这里找不到答案:/
我想通过串行接口(Serial.read())向我的arduino发送一个由逗号分隔的三个数字的简单字符串.这三个数字的范围可以是0-255.
例如.
255,255,255
0,0,0
1,20,100
90,200,3
我需要做的是将发送到arduino的字符串解析为三个整数(比方说r,g和b).
所以当我发送100,50,30时,arduino会把它翻译成
int r = 100
int g = 50
int b = 30
Run Code Online (Sandbox Code Playgroud)
我尝试了很多代码,但没有一个能够工作.主要问题是将字符串(字符串)转换为整数.我发现可能会有strtok_r用于分隔符目的,但那是关于它的.
谢谢你的任何建议:)
dsn*_*ton 20
要回答您实际问过的问题,String对象非常强大,它们可以完全按照您的要求执行.如果直接从输入中限制解析规则,则代码将变得不那么灵活,可重用性降低,并且会有轻微的错综复杂.
字符串有一个名为indexOf()的方法,它允许您在特定字符的字符串字符数组中搜索索引.如果未找到该字符,则该方法应返回-1.可以将第二个参数添加到函数调用中以指示搜索的起始点.在你的情况下,因为你的分隔符是逗号,你会打电话给:
int commaIndex = myString.indexOf(',');
// Search for the next comma just after the first
int secondCommaIndex = myString.indexOf(',', commaIndex + 1);
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用该索引使用String类的substring()方法创建子字符串.这将返回一个从特定起始索引开始的新String,并在第二个索引之前结束(如果没有给出,则返回文件末尾).所以你会输入类似于:
String firstValue = myString.substring(0, commaIndex);
String secondValue = myString.substring(commaIndex + 1, secondCommaIndex);
String thirdValue = myString.substring(secondCommaIndex + 1); // To the end of the string
Run Code Online (Sandbox Code Playgroud)
最后,可以使用String类的未记录方法toInt()来检索整数值:
int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();
Run Code Online (Sandbox Code Playgroud)
有关String对象及其各种方法的更多信息,请参阅Arduino文档.
小智 6
使用sscanf;
const char *str = "1,20,100"; // assume this string is result read from serial
int r, g, b;
if (sscanf(str, "%d,%d,%d", &r, &g, &b) == 3) {
// do something with r, g, b
}
Run Code Online (Sandbox Code Playgroud)
如果要解析字符串ex:解析函数以逗号分隔的字符串,请在此处使用我的代码255,255,255 0,0,0 1,20,100 90,200,3
我想你想做这样的事情来读取数据:
String serialDataIn;
String data[3];
int counter;
int inbyte;
void setup(){
Serial.begin(9600);
counter = 0;
serialDataIn = String("");
}
void loop()
{
if(serial.available){
inbyte = Serial.read();
if(inbyte >= '0' & inbyte <= '9')
serialDataIn += inbyte;
if (inbyte == ','){ // Handle delimiter
data[counter] = String(serialDataIn);
serialDataIn = String("");
counter = counter + 1;
}
if(inbyte == '\r'){ // end of line
handle end of line a do something with data
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用atoi()将数据转换为整数并使用它们。
| 归档时间: |
|
| 查看次数: |
67329 次 |
| 最近记录: |