我正在尝试使用 C++ 程序使用串口读取 arduino 发送的数据。 我可以看到 Arduino 正在发送一些数据; devStatus 变量显示非零值并且 dwRead 正在更新为 4,但缓冲区仍然为空。我已经尝试了很多东西,比如使用 COMMTIMEOUTS 结构设置超时。 这是我的 Arduino 代码:
#include<stdio.h>
#include<conio.h>
#include<windows.h>
int main(int argc, char** argv)
{
HANDLE hCOM;
DCB dcb;
BOOL bPortReady;
hCOM = CreateFile("\\\\.\\COM15",GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
bPortReady = SetupComm(hCOM,10,128);
bPortReady = GetCommState(hCOM, &dcb);
//populate variables in the DCB strucutre
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fAbortOnError = TRUE;
dcb.fOutX = FALSE;
dcb.fInX = FALSE;
dcb.fOutxCtsFlow = FALSE;
dcb.fRtsControl = FALSE;
dcb.fOutxDsrFlow = FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
bPortReady = GetCommState(hCOM, &dcb);
char lpBuffer[5];
DWORD dwRead;
COMSTAT devStatus;
BOOL rFile;
ClearCommError(hCOM, NULL, &devStatus);
if(devStatus.cbInQue>0)
{
//The read function returns true, but no Data is getting read.
rFile = ReadFile( hCOM , &lpBuffer , 4, &dwRead,0);
printf("Read : %s",lpBuffer);
}
else
printf("Nothing in queue");
_getch();
}
请原谅我的格式和糟糕的编程技巧,我是一名外科医生,一直在努力学习编程,这是我在这里的第一篇文章。
最佳答案
您发布的代码两次调用 GetCommState。我想你打算为第二个调用 SetCommState。
另一个问题是 printf 期望缓冲区以 nul ('\0') 终止。因此,在将缓冲区或 lpBuffer[dwRead] 传递给 printf 之前将其清零。
如果 dwRead 返回 4,那么您确实得到了 4 个字节。使用调试器查看缓冲区中的内容。可能不是可打印的字符。
关于c++ - 无法从 Arduino 读取数据到 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25796550/