繁体   English   中英

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

[英]Reading serial data from an Arduino using C++

这就是我想要做的。 我已经有一些功能,例如,该功能可以将数据写入串行端口,该功能可以完美运行:

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/Interface/CPPWindows

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

这就是我的问题,我可以将数据写入串行,但无法读取,该怎么办?

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

增加一个睡眠(10); 在从计算机上冲掉端口之前,它足以最终读取数据。

感谢@Matts的帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM