[英]Reading from Arduino Serial seems to be very unstable
I have the following simple code to read commands sent from the computer to an Arduino Mega board: 我有以下简单的代码来读取从计算机发送到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
}
}
}
The commands are like A123 B123 C123 D123\\n 命令类似于A123 B123 C123 D123 \\ n
Basically a sequence of space separated instructions, were each instruction starts by a letter and follows by a number. 基本上是一系列由空格分隔的指令,每个指令以字母开头,后跟数字。 A command ends with a "\\n".
命令以“ \\ n”结尾。
Reading this seems to be very unstable. 读这篇文章似乎很不稳定。 Sometimes I get the command perfectly, sometimes I miss the first letter, sometimes a pair of them, sometimes it starts by the number,...
有时我会完美地获得命令,有时会错过第一个字母,有时会错过一对字母,有时会以数字开头,...
I am sending the commands through the serial monitor, set to newline. 我正在通过串行监视器发送命令,并将其设置为换行符。
Before having this code, I'd simply check for the size using Serial.available, then Id wait a second to fill the buffer, and then I'd copy the buffer to a char*. 在获得此代码之前,我只需使用Serial.available检查大小,然后等待一秒钟以填充缓冲区,然后将缓冲区复制到char *。 This worked flawlessly.
这完美无瑕。 I am doing now this loop waiting for a \\n, which seems more elegant, but it is being very unstable.
我现在正在执行此循环,等待\\ n,这看起来更优雅,但它非常不稳定。
Code works by simply adding a delay(100) after the first Serial.available() 代码只需在第一个Serial.available()之后添加一个delay(100)即可工作
This is the code: 这是代码:
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
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.