串口通讯Arduino, c++

Serial port communication Arduino, C++

本文关键字:c++ Arduino 串口      更新时间:2023-10-16

好吧,我遇到了一个问题。我在用微软飞行模拟器X SDK和Arduino编程。应用程序应该通过串行端口将数据发送到arduino板,我使用以下功能:

http://playground.arduino.cc/Interfacing/CPPWindows

程序工作得很好,除了它突然停止工作。这个程序是一个循环while(1),它连续地执行一个函数,向模拟器请求数据,然后通过serial发送一个字符串。这是我调用函数WriteData的方式:

WriteData((char *)cadena.c_str(),8);

表示我发送的字符串cadena。函数WriteData是这样的:

bool Serial::WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;
    //Try to write the buffer on the Serial port
    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        //In case it don't work get comm error and return false
        ClearCommError(this->hSerial, &this->errors, &this->status);
        return false;
    }
    else
        return true;
    }

我已经看到,如果我评论整个if-else,所以函数WriteFile永远不会被调用,程序不会停止工作并继续完美(除了信息没有发送到Arduino的事实)。如果执行了这一行,那么程序将在大约一分钟后停止。我说的停止不是指崩溃或其他什么,我只是指它停止了,控制台仍然在那里,所有的消息,它只是停止工作。

发生了什么事?

编辑:好的,arduino也连续发送数据,从未被程序读取,这可能是一个问题吗?可能是缓冲区已满,WriteFile正在等待空间写入吗?,因为我知道我不写串行,它似乎工作得很好…

WriteFile()将在传输缓冲区被填满时停止。只有当你正确设置握手时,它才会清空。要么用电,连接DSR和CTS信号,这在Arduino上往往被跳过。或者通过禁用握手,SetCommState()函数。使用SetCommTimeouts()设置超时是另一种适当的策略,可以添加一些最小的错误恢复。

不读取Arduino发送的数据也不会得到很多分。最好是逐步实现,这样您就可以一次专注于解决一个问题。然而,它通常不能阻止PC传输数据,模握手接线错误。