我极力尝试让arduino将处理中的字符串划分为两组变量。在下面的代码中,我决定只键入重要部分,但是x和y当然包含正确的值。任何解决方案将不胜感激。到目前为止,这是我的两次尝试:
尝试1根本不起作用。1.处理:
myPort.write(x + "," + y + "\n");
1.Arduino:
String tempX = Serial.readStringUntil(44);
String tempY = Serial.readStringUntil(10);
String x = tempX.substring(0,tempX.length() -1);
String y = tempY.substring(0,tempY.length() -1);
尝试2,x可以正常工作,但y不能工作。2.处理:
String [] dataToSend = new String [2];
dataToSend [0] = x;
dataToSend [1] = y;
String joinedData = join(dataToSend, ":");
myPort.write(joinedData);
2.Arduino:
String x = Serial.readStringUntil(":");
Serial.read(); //next character is comma, so skip it using this
String y = Serial.readStringUntil('\0');
首先,不用担心在处理端将它们组合在一起。紧接着发送两个字符串与发送一个长字符串相同。所有这些都在串行行上被分解为字节,没有人知道一个打印行在哪里停止,下一个开始在哪里。
myport.write(x);
myport.write(',');
myport.write(y);
myport.write('\n')
将同样有效。
然后在Arduino方面,您最有可能想回避String类。逐字符读取数据到char数组中。
char myArray[howLongTheStringIs];
char x[howLongXIs];
char y[howLongYIs];
int index = 0;
这会在循环中反复调用,并在输入串行数据时对其进行拾取:
while (Serial.available()){
char c = Serial.read();
myArray[index] = c; // add c to the string
myArray[++index] = 0; // null terminate our string
if(c == '\n'){ // if we are at the end of the string
handleString();
}
}
然后您有一个解析字符串的函数,有很多方法可以做到这一点:
如果您对分隔符以外的字符串一无所知,请使用strtok:
void handleString(){
char* ptr = strtok(myArray, ":"); // get up to the ":" from the string
strcpy(x, ptr); // copy into x
ptr = strtok(NULL, "\n"); // get from the separator last time up to the next "\n"
strcpy(y, ptr); // copy into y
index = 0 // reset our index and
myArray[0] = 0; // and clear the string
}
所有内容都未经测试,未经编译,都写在回复框中,因此,如果我在其中输入了一些错字,请原谅和纠正。但是这样的事情应该起作用。如果您已经知道字符串的确切长度(或可以从处理代码发送它们),则handleString方法可以更简单。如果您与x和y有一些短小的关系,并且在此之后不需要它们,那么您可以只保留指向它们在myArray中的位置的指针。这完全取决于代码的总体目标。但是这样的事情应该可以完成工作。