// 串口 向 9329 发送 键盘和鼠标信息 ==================
// BOOL OpenCom() 打开串口
// void Set_Com () 初始化 串口 参数
// int Read_Com( ) 读串口数据
// int Write_Com() 写串口数据
HANDLE hCom; //全局变量,串口句柄
HANDLE OpenCom() {
HANDLE hCom = CreateFile(L"COM3",
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if (hCom == (HANDLE)-1) {
return NULL;
}
return hCom ;
}
// 设置串口 超时
void Set_Com(HANDLE hCom) {
SetupComm(hCom, 1024, 1024); //输入缓冲区和输出缓冲区的大小都是1024
COMMTIMEOUTS TimeOuts; //设定读超时
TimeOuts.ReadIntervalTimeout = 1000;
TimeOuts.ReadTotalTimeoutMultiplier = 500;
TimeOuts.ReadTotalTimeoutConstant = 5000; //设定写超时
TimeOuts.WriteTotalTimeoutMultiplier = 500;
TimeOuts.WriteTotalTimeoutConstant = 2000;
SetCommTimeouts(hCom, &TimeOuts); //设置超时
DCB dcb;
GetCommState(hCom, &dcb);
dcb.BaudRate = 9600; //波特率为9600
dcb.ByteSize = 8; //每个字节有8位
dcb.Parity = NOPARITY; //无奇偶校验位
dcb.StopBits = TWOSTOPBITS; //两个停止位
SetCommState(hCom, &dcb); // 写入 设置数据
PurgeComm(hCom, PURGE_TXCLEAR | PURGE_RXCLEAR); // 清理 串口接受(Rx)和发送(Tx)缓冲区
}
int Read_Com(HANDLE hCom ){
char lpInBuffer[1024];
DWORD dwBytesRead = 1024;
COMSTAT ComStat;
DWORD dwErrorFlags;
OVERLAPPED m_osRead;
memset(&m_osRead, 0, sizeof(OVERLAPPED));
m_osRead.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
ClearCommError(hCom, &dwErrorFlags, &ComStat);
dwBytesRead = min(dwBytesRead, (DWORD)ComStat.cbInQue);
if (!dwBytesRead) return FALSE;
BOOL bReadStatus;
bReadStatus = ReadFile(hCom, lpInBuffer, dwBytesRead, &dwBytesRead, &m_osRead);
if (!bReadStatus) {
//如果ReadFile函数返回FALSE
if (GetLastError() == ERROR_IO_PENDING)
{
//GetLastError()函数返回ERROR_IO_PENDING,表明串口正在进行读操作
WaitForSingleObject(m_osRead.hEvent, 2000);
//使用WaitForSingleObject函数等待,直到读操作完成或延时已达到2秒钟
//当串口读操作进行完毕后,m_osRead的hEvent事件会变为有信号,
PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
return dwBytesRead;
}
return 0;
}
PurgeComm(hCom, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR | PURGE_RXCLEAR);
return dwBytesRead;
}
int Write_Com(HANDLE hCom, unsign wchar_t* buffer) {
DWORD dwBytesWritten = 1024;
DWORD dwErrorFlags;
COMSTAT ComStat;
OVERLAPPED m_osWrite;
BOOL bWriteStat;
bWriteStat = WriteFile(hCom, buffer, dwBytesWritten, &dwBytesWritten, &m_osWrite);
if (!bWriteStat)
{
if (GetLastError() == ERROR_IO_PENDING)
{
WaitForSingleObject(m_osWrite.hEvent, 1000);
return dwBytesWritten;
}
return 0;
}
return dwBytesWritten;
}