我正在尝试从我的Arduino读取传感器数据并通过USB发送命令使其运行它的电机和伺服器。当我没有向PC发送任何传感器数据时,它似乎工作正常,但是当我开始发送数据时,它停止对命令执行操作,通常电机将不会停止运行,直到我重新启动Arduino。
这是我的代码:
unsigned long serialdata;
int inbyte;
int packetIndex;
int packet[5];
float magOutput[4];
float mpuOutput[7];
long outputMillis = 0;
char openChar = '{';
char closeChar = '}';
char seperatorChar = '/';
bool isRecieving = false;
bool packetWaiting = false;
void recieveSerial() {
if (packetWaiting) {
return;
}
inbyte = Serial.read();
if (!isRecieving) {
if (inbyte == openChar) {
isRecieving = true;
packetIndex = 0;
serialdata = 0;
}
return;
}
if (inbyte == seperatorChar) {
packet[packetIndex] = serialdata;
packetIndex++;
serialdata = 0;
return;
}
if (inbyte == closeChar) {
packetWaiting = true;
isRecieving = false;
return;
}
if (inbyte > 0) {
serialdata = serialdata * 10 + inbyte - '0';
}
}
void sendSerial() {
unsigned long currentMillis = millis();
if (currentMillis - outputMillis > 20) {
outputMillis = currentMillis;
Serial.print(openChar + '0' + seperatorChar);
for (int i = 0; i < 3; i++) {
Serial.print(magOutput[i]);
Serial.print(seperatorChar);
}
Serial.print(magOutput[3]);
Serial.println(seperatorChar);
Serial.print('1' + seperatorChar);
for (int i = 0; i < 6; i++) {
Serial.print(mpuOutput[i]);
Serial.print(seperatorChar);
}
Serial.print(mpuOutput[6]);
Serial.println(seperatorChar + closeChar);
Serial.flush();
}
}
当我按下向上箭头时,PC发送这样的命令,'{0/0/1/255}',如{motor / motor 1 / forwards / speed 255}。
有没有办法确保Arduino在向PC发送数据时接收并执行我的命令?