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

3

这就是我想要做的事情。我已经有了一些函数,例如用于向串行端口写入数据的函数,它可以完美地工作:

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,所以我的函数基本相同。我只是将它们复制到我的代码中而不是使用它们作为类对象,但更重要的是它们是相同的。所以这就是我的问题,我可以向串口写入数据,但无法读取,我该怎么办?

你打开串口的代码是什么样子的?GetLastError函数返回了什么信息?你确定设备确实在向你发送数据吗? - Mats Petersson
@MatsPetersson hSerial = CreateFile(wText, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);hSerial是一个变量,定义为HANDLE hSerial。你的意思是这个吗? - MyUserIsThis
你应该意识到,在你的读取函数中省略了获取状态的行,这可能意味着检查 cbInQue 的 if 语句将失败。 - Mats Petersson
你需要注意SetCommState()函数。如果硬件握手被启用且Arduino未打开RTS和DTR信号,那么你将不会收到任何东西。 - Hans Passant
@HansPassant 非常感谢您的帮助。实话实说,我不知道那些是什么,但我打算学习它们,因为我计划编写一些需要了解串行通信的程序。无论如何,我刚刚解决了这个问题,结果只是在写入读取数据之间的时间问题。我会回答这个问题。再次感谢您的帮助。顺便说一句,如果您知道任何可以让我学习所有这些内容的好在线资料,我将非常感激。再次感谢您,再见。 - MyUserIsThis
显示剩余2条评论
1个回答

2

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

在从计算机读取端口之前添加Sleep(10);就足以最终读取数据。

感谢@Matts的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接