69,371
社区成员
发帖
与我相关
我的任务
分享
//打开串口
hCOM = CreateFile("\\\\.\\COM3", GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hCOM == INVALID_HANDLE_VALUE)
{
if ((i = GetLastError()) == 2)
MessageBox(GetForegroundWindow(), TEXT("该串口不存在"), TEXT("操作失败"), MB_ICONINFORMATION);
else if (i == 5)
MessageBox(GetForegroundWindow(), TEXT("该串口已被占用"), TEXT("操作失败"), MB_ICONINFORMATION);
else
MessageBox(GetForegroundWindow(), TEXT("无法打开串口"), TEXT("操作失败"), MB_ICONINFORMATION);
return TRUE;
}
if (PurgeComm(hCOM, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR) == 0)
{
MessageBox(GetForegroundWindow(), TEXT("清除串口缓冲区出错"), TEXT("操作失败"), MB_ICONINFORMATION);
return TRUE;
}
//设置串口的波特率等等
if (!GetCommState(hCOM, &dcb))
{
MessageBox(GetForegroundWindow(), TEXT("无法获取串口状态"), TEXT("操作失败"), MB_ICONINFORMATION);
hCOM = INVALID_HANDLE_VALUE;
return TRUE;
}
dcb.BaudRate = 9600;
dcb.ByteSize = 8;
dcb.Parity = NOPARITY;
dcb.StopBits = ONESTOPBIT;
if (!SetCommState(hCOM, &dcb))
{
MessageBox(GetForegroundWindow(), TEXT("无法设置串口状态"), TEXT("操作失败"), MB_ICONINFORMATION);
hCOM = INVALID_HANDLE_VALUE;
return TRUE;
}
//设置串口超时
COMMTIMEOUTS communication_timeout;
communication_timeout.ReadIntervalTimeout=MAXDWORD;
communication_timeout.ReadTotalTimeoutMultiplier=200;
communication_timeout.ReadTotalTimeoutConstant=1000;
communication_timeout.WriteTotalTimeoutMultiplier=0;
communication_timeout.WriteTotalTimeoutConstant=0;
if (!SetCommTimeouts(hCOM, &communication_timeout))
{
MessageBox(GetForegroundWindow(), TEXT("无法设置串口超时"), TEXT("操作失败"), MB_ICONINFORMATION);
hCOM = INVALID_HANDLE_VALUE;
return TRUE;
}
//清除串口缓冲区
if (PurgeComm(hCOM, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR) == 0)
{
MessageBox(GetForegroundWindow(), TEXT("清除串口缓冲区出错"), TEXT("操作失败"), MB_ICONINFORMATION);
return FALSE;
}
//发送数据
BYTE cDataBuf[6];
DWORD dwBytesWriten, dwBytesReaded;
cDataBuf[0] = 0x55;
cDataBuf[1] = bType;
cDataBuf[2] = 0xff;
cDataBuf[3] = 0xff;
cDataBuf[4] = 0xff;
cDataBuf[5] = 0xaa;
WriteFile(hCOM, cDataBuf, 6, &dwBytesWriten, NULL);
//接收数据
ReadFile(hCOM, cDataBuf, 6, &dwBytesReaded, NULL);