如果我要让程序能够无限等待或超时等待,到串口有数据输入的时候再去读取串口该怎么办?
下面是我的代码
#include <Windows.h>
#include <tchar.h>
#include <iostream>
#include <cstring>
#define BUFF_SIZE 512
using namespace std;
int main()
{
HANDLE hCOM;
DCB setting;
COMMTIMEOUTS timeout;
DWORD wCount, com_mask;
char buffer[BUFF_SIZE];
COMSTAT Comstat;
DWORD dwErrorFlags;
hCOM = CreateFile(_T("COM3"), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hCOM == (HANDLE)-1)
{
cout << "Open COM1 failed" << endl;
getchar();
return -1;
}
SetupComm(hCOM, 550, 550);
timeout.ReadIntervalTimeout = 1;
timeout.ReadTotalTimeoutConstant = 0;
timeout.ReadTotalTimeoutMultiplier = 0;
timeout.WriteTotalTimeoutConstant = 0;
timeout.WriteTotalTimeoutMultiplier = 0;
SetCommTimeouts(hCOM, &timeout);
memset(&setting, 0, sizeof(DCB));
setting.BaudRate = CBR_115200;
setting.fParity = 0;
setting.Parity = NOPARITY;
setting.ByteSize = 8;
setting.StopBits = ONESTOPBIT;
SetCommState(hCOM, &setting);
PurgeComm(hCOM, PURGE_TXCLEAR|PURGE_RXCLEAR);
ClearCommError(hCOM, &dwErrorFlags, &Comstat);
ResetEvent(hCOM);
while (1)
{
wCount = 0;
memset(buffer, 0, BUFF_SIZE);
ReadFile(hCOM, (void *)buffer, BUFF_SIZE, &wCount, NULL);
if (wCount <= 0)
{
cout << "--no receice" << endl;
continue;
}
cout << "--received " << wCount << ":";
for (int i = 0; i < wCount ; ++i)
{
cout << buffer[i];
}
cout << endl << endl;
}
getchar();
CloseHandle(hCOM);
return 0;
}
4 个解决方案
#2
可是如果用WaitCommEvent 就没有等待超时的功能。我还需要等待一段时间,如果串口没有数据就不读串口。求大牛赐教。
#4
最后改成了用重叠模式,但是每次读数据的时候都要用CreateEvent向内核申请资源,感觉有点麻烦而且不太安全
#1
串口用
WaitCommEvent
#2
可是如果用WaitCommEvent 就没有等待超时的功能。我还需要等待一段时间,如果串口没有数据就不读串口。求大牛赐教。
#3
建议阅读下官方文档
Serial Communications in Win32
#4
最后改成了用重叠模式,但是每次读数据的时候都要用CreateEvent向内核申请资源,感觉有点麻烦而且不太安全