我一直在尝试实现我的基于arduino的项目和我的pc之间的串行通信,我需要通过串行向arduino发送命令,并使用"if和else"来调用所需的函数(在parseMessage()函数中)。
我不能使用delay(),因为我正在使用中断进行多路复用和位角调制,所以我必须以另一种方式进行串行通信,这是最接近成功的,但我仍然得到字符跳过和一般不稳定。正如你所知道的,编码是伟大的,除了当你不知道你的代码有什么问题的时候,所以帮帮我,请互联网的上帝!;)
我使用'#'作为字符串声明结束的原因是,我不能确定当serial .read()请求时发送给arduino的命令的所有字符都在那里,可能会有更多的方式,并且由于atmega328比串行端口更快。serial .available()实际上可能在传输过程中返回-1。
-
ps:哦,我不能使用字符串类,它非常昂贵,这个atmega328已经在8x8 RGBLED多路复用和4位角调制下出汗,他将来必须做更多。
-
ps:我还在学习英语,所以如果我使用的语法有问题,请原谅我。
void setup() { Serial.begin(9600); } bool dataRTP = false; // data ready to parse void loop() { readSerial(); } char message[64]; int index = 0; void readSerial() { if (Serial.available() > 0) while (Serial.available() > 0) if (Serial.peek() != '#') // i'm using '#' as end of string declearation. message[index++] = Serial.read(); else { message[index++] = 'n'; dataRTP = true; break; } while (Serial.read() != -1) {} // flushing any possible characters off of if (dataRTP) // UARTS buffer. parseMessage(); } void parseMessage() { // just testing here, actual code would be like : Serial.print(message); // if (!strcmp(message, "this expression")) index = 0; // callthisfunction(); dataRTP = false; // else ... etc }
刚刚设法修复了这段代码,似乎从串行UART中冲洗数据毕竟不是一个好主意。一切都解决了。下面是代码现在的样子:
void setup() {
Serial.begin(9600);
}
bool dataRTP = false;
void loop() {
readSerial();
}
char message[64];
int index = 0;
void readSerial() {
if (Serial.available() > 0)
while (Serial.available() > 0)
if (Serial.peek() == '#') {
message[index++] = Serial.read();
message[index++] = ' ';
dataRTP = true;
break;
}
else
message[index++] = Serial.read();
if (dataRTP)
parseMessage();
}
void parseMessage() {
Serial.println(message);
index = 0;
dataRTP = false;
}