前端之家收集整理的这篇文章主要介绍了
windows C++ 串口通信基本代码,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
HANDLE hCom = CreateFile(L"\\\\.\\COM4",GENERIC_READ | GENERIC_WRITE,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if (hCom == INVALID_HANDLE_VALUE){
DWORD dwErr = GetLastError();
char cData[2048] = {0};
sprintf(cData,"打开串口失败:%d",dwErr);
OutPut(NORMAL_LOG,cData);
return false;
}
//设置读超时
COMMTIMEOUTS timeouts;
GetCommTimeouts(hCom,&timeouts);
timeouts.ReadIntervalTimeout = 0;
timeouts.ReadTotalTimeoutMultiplier = 0;
timeouts.ReadTotalTimeoutConstant = 60000;
timeouts.WriteTotalTimeoutMultiplier = 0;
timeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(hCom,&timeouts);
//设置读写缓冲区大小
static const int g_nZhenMax = 32768;
if (!SetupComm(hCom,g_nZhenMax,g_nZhenMax)){
DWORD dwErr = GetLastError();
char cData[2048] = { 0 };
sprintf(cData,"设置读写缓冲区大小失败:%d",cData);
CloseHandle(hCom);
return false;
}
//设置串口配置信息
DCB dcb;
if (!GetCommState(hCom,&dcb)){
DWORD dwErr = GetLastError();
char cData[2048] = { 0 };
sprintf(cData,"设置串口配置信息失败:%d",cData);
CloseHandle(hCom);
return false;
}
dcb.DCBlength = sizeof(DCB);
dcb.BaudRate = 9600;//波特率为9600
dcb.Parity = 0;//校验方式为无校验
dcb.ByteSize = 8;//数据位为8位
dcb.StopBits = ONESTOPBIT;//停止位为1位
if (!SetCommState(hCom,cData);
CloseHandle(hCom);
return false;
}
//清空缓冲
PurgeComm(hCom,PURGE_RXCLEAR | PURGE_TXCLEAR);
//清除错误
DWORD dwError;
COMSTAT cs;
if (!ClearCommError(hCom,&dwError,&cs)){
CloseHandle(hCom);
return false;
}
//设置串口监听事件
SetCommMask(hCom,EV_RXCHAR);
DWORD dwWrite = 0;
unsigned char btCMD_OpenDoor[4] = { 0xa0,0x01,0xa2 };
unsigned char btCMD_CloseDoor[4] = { 0xa0,0x00,0xa1 };
while (true){
if (WaitForSingleObject(pMain->m_hCLOSE_ALL_THREAD,10) == WAIT_OBJECT_0){
break;
}
WriteFile(hCom,btCMD_OpenDoor,4,&dwWrite,NULL);
Sleep(1000);
WriteFile(hCom,btCMD_CloseDoor,NULL);
}
WriteFile(hCom,NULL);
CloseHandle(hCom);