c++ - 使用 C++ 从 Arduino 读取串行数据

标签 c++ serial-port arduino

这就是我想做的。我已经有了一些功能,例如这个将数据写入串行端口的功能,它工作得很好:

bool WriteData(char *buffer, unsigned int nbChar)
{
    DWORD bytesSend;

    //Try to write the buffer on the Serial port
    if(!WriteFile(hSerial, (void *)buffer, nbChar, &bytesSend, 0))
    {
        return false;
    }
    else
        return true;
}

读取函数是这样的:

int ReadData(char *buffer, unsigned int nbChar)
{
//Number of bytes we'll have read
DWORD bytesRead;
//Number of bytes we'll really ask to read
unsigned int toRead;

ClearCommError(hSerial, NULL, &status);
//Check if there is something to read
if(status.cbInQue>0)
{
    //If there is we check if there is enough data to read the required number
    //of characters, if not we'll read only the available characters to prevent
    //locking of the application.
    if(status.cbInQue>nbChar)
    {
        toRead = nbChar;
    }
    else
    {
        toRead = status.cbInQue;
    }

    //Try to read the require number of chars, and return the number of read bytes on success
    if(ReadFile(hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
    {
        return bytesRead;
    }

}

//If nothing has been read, or that an error was detected return -1
return -1;

}

而且无论我用 arduino 做什么,这个函数总是返回 -1,我什至尝试加载一个不断向串口写入字符的代码,但没有任何结果。

我从这里得到了函数:http://playground.arduino.cc/Interfacing/CPPWindows

所以我的功能基本一样。我只是将它们复制到我的代码中,而不是将它们用作类对象,但不仅如此,它们是相同的。

所以这是我的问题,我可以将数据写入串口但无法读取,我可以尝试什么?

最佳答案

对于任何感兴趣的人,我已经解决了它,这是一个愚蠢的错误。我对 Arduino 进行了编程,因此它会在发送任何内容之前等待串行输入。计算机程序一行一行地编写和发送代码,我猜 i7 比 Atmel 更快......显然数据需要一些时间。

添加 sleep (10);在从计算机重新连接端口之前足以最终读取数据。

感谢@Matts 的帮助。

关于c++ - 使用 C++ 从 Arduino 读取串行数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16318069/

相关文章:

java - 尝试在 Raspberry Pi 上运行 Arduino IDE 时出错

C++ 通过引用 dll 中的函数传递 std::string

c++17:至少必须替换哪些版本的全局运算符 new/delete 以覆盖所有情况?

c++ - CMake "make install"或在 Windows 中包含一个库

c++ - 如何将 QSerialPort 模块添加到 CMake 中?

java - 在Linux 64位下使用Java实现串口工作

serial-port - void serialEvent Arduino - 处理以避免滞后

c++ - Arduino编程添加毫秒延迟

c++ - SDL_GL_SwapBuffers() 间歇性变慢

c++ - 在 Platformio 上使用串行监视器不显示 tty.usbmodem