将Processing到Arduino的两组字符串数据接收为两个变量



我拼命想让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('');

首先,不要担心在处理端组合它们。一个接一个地发送两个字符串与发送一个长字符串相同。所有这些都在串行线上被分解成字节,没有人能说出一行打印在哪里停止,下一行打印从哪里开始。

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中的位置的指针。这完全取决于你的代码的总体目标是什么。但这样的事情应该能完成任务。

最新更新