[英]Reading serial data from an Arduino using C++
So that's what I want to do. 这就是我想要做的。 I already have some functions, for example this one to write data to the serial port, which works perfectly:
我已经有一些功能,例如,该功能可以将数据写入串行端口,该功能可以完美运行:
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;
}
The reading function is like this: 阅读功能是这样的:
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;
}
And no matter what I do with the arduino, this function always returns -1, I even tried loading a code that constantly writes a character to the serial port, but nothing. 不管我使用arduino做什么,该函数总是返回-1,我什至尝试加载一个不断向串行端口写入字符的代码,但是什么也没有。
I got the functions from here: http://playground.arduino.cc/Interfacing/CPPWindows 我从这里获得功能: http : //playground.arduino.cc/Interface/CPPWindows
so my functions are basically the same. 所以我的功能基本相同。 I just copied them into my code instead of using them as classes objects, but more than that it's the same.
我只是将它们复制到我的代码中,而不是将它们用作类对象,但除此之外,它是相同的。
So that's my problem, I can write data to the serial but I can't read, what can I try? 这就是我的问题,我可以将数据写入串行,但无法读取,该怎么办?
For anyone interested, I already solved it and it was a silly mistake. 对于任何感兴趣的人,我已经解决了它,这是一个愚蠢的错误。 I programmed the Arduino so it would wait for a serial input before sending anything.
我对Arduino进行了编程,因此它将在发送任何内容之前等待串行输入。 The computer program writes and sends one line of code after another, and I guess a i7 is faster than the Atmel... and obviously the data takes some time.
该计算机程序编写并发送另一行代码,我猜i7比Atmel更快...显然,数据需要一些时间。
Adding a Sleep(10); 增加一个睡眠(10); before reding the port from the computer was enough to finally read the data.
在从计算机上冲掉端口之前,它足以最终读取数据。
Thanks to @Matts for his help. 感谢@Matts的帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.