我有以下简单代码来读取从计算机发送到 Arduino Mega 开发板的命令:
void get_command()
{
char received;
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received == '\n') {
buffer[index] = '\0';
parse_command(buffer);
} else {
buffer[index++] = received;
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
指令如A123 B123 C123 D123\n
基本上是一系列空格分隔的指令,每条指令都以字母开头,后跟数字。命令以“\n”结尾。
读这个好像很不稳定。有时我完美地得到了命令,有时我错过了第一个字母,有时是一对,有时它以数字开头,...
我正在通过串行监视器发送命令,设置为换行符。
在编写此代码之前,我会使用 Serial.available 检查大小,然后等待一秒钟来填充缓冲区,然后将缓冲区复制到 char*。这完美无缺。我现在正在做这个循环等待一个\n,这看起来更优雅,但它非常不稳定。
最佳答案
代码的工作原理是在第一个 Serial.available() 之后简单地添加一个 delay(100)
这是代码:
void get_command()
{
char received;
if (Serial.available() > 0) {
delay(100); // let the buffer fill up
int index = 0;
while (Serial.available() > 0) {
if (index < BUFFER_SIZE -1) {
received = Serial.read();
if (received != '\n') {
buffer[index] = received;
index++;
} else {
buffer[index] = '\0';
parse_command(buffer);
}
} else {
Serial.println('666'); // buffer overflow
}
}
}
}
关于c++ - 从 Arduino Serial 读取似乎很不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24741765/