在App Inventor中,如何确保收到整个字符串?
我一直在Arduino和Android应用程序之间发送文本命令。我在Arduino上使用了一个函数,它确保整个命令在进一步处理之前到达:
(图片来源:@Robin2)
const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;
void setup() {
Serial.begin(38400);
}
void loop() {
read_serial();
}
void read_serial() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
} else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
char * strtokIndx;
strtokIndx = strtok(receivedChars, ":");
int section = atoi(strtokIndx);
strtokIndx = strtok(NULL, ":");
int action = atoi(strtokIndx);
strtokIndx = strtok(NULL, ":");
int value = atoi(strtokIndx);
do_something_with(section, action, value);
}
} else if (rc == startMarker) {
recvInProgress = true;
}
}
}
现在,如何在App Inventor中复制此功能,以确保时钟计时器不会将文本命令拆分为多个部分?
App Inventor(时钟为100毫秒):
例:
Arduino(这部分经常发射):
my_function(){
Serial.print(NUMBER);
Serial.print(":");
Serial.print(ANOTHER_NUMBER);
Serial.print(":");
Serial.println(YET_ANOTHER_NUMBER);
}
我的Android应用中的测试输出:
- 1:3:150
- 1:3:150
- 1:3:150
- 1:3:1
- 50
- 1:3:150
- ...
如您所见,第4个命令已被拆分为多个部分。我该如何防止这种情况?
最后,设计了工作方案。
想法是发送文本模式命令:<
start command
end >
然后在App Inventor中:
BTCommand
变量设置为空字符串BTCommand
<
字符串中检查天气>
和BTCommand
的调用函数BTCommand
字符串拆分为命令BTCommand
字符串中删除它们<com
,保持在BTCommand
字符串,等待mand>
,并在下次调用它。