c++ - 从 Arduino Serial 读取似乎很不稳定

标签 c++ serial-port arduino

我有以下简单代码来读取从计算机发送到 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/

相关文章:

c++ - 使用 OpenGL 无法正确显示三角形带

c++ - 我应该在类里面使用 `this` 吗?

arduino - 我的程序中需要多线程吗?

c++ - 使用 Qt5 编译 Qt3D 失败

c++ - 我们可以像这样初始化一个 C++ 对象吗?

c# - 将许多变量从 Unity 发送到 Arduino

java - PrintWriter 到 JTextArea,在调用的方法关闭之前不会显示任何内容

c++ - 与 QSerialPort 的基本通信

javascript - 如何让步进电机随时间转动360度?

c++ - 可以像普通相机一样使用 pixy