声明:
HANDLE m_hCom; // 串口句柄
OVERLAPPED m_osRead,m_osWrite; // 指向重叠结构变量的指针
打开串口:
CString strCom;
m_Com.GetWindowText(strCom);
m_hCom=CreateFile(strCom,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,
NULL);
if(m_hCom==INVALID_HANDLE_VALUE)
{
MessageBox("打开串口失败!","错误",MB_OK|MB_ICONERROR);
return;
}
SetupComm(m_hCom,1024,512);
发送数据:
bool fState;
DWORD length=dwlength;// 数据长度
byte bytSendAddress;
byte bytSendData[32];
int i, j;
j = 0;
bytSendAddress = buf[0];
for(i=1;i<=length;i++)
{
bytSendData[j] = buf[i];
j++;
}
DCB myDCB;
GetCommState(m_hCom,&myDCB);
myDCB.BaudRate = CBR_4800;
myDCB.fBinary = TRUE;
myDCB.fParity = TRUE;
myDCB.ByteSize = 8;
myDCB.Parity = MARKPARITY;
myDCB.StopBits = ONESTOPBIT;
SetCommState(m_hCom,&myDCB);
fState=WriteFile(m_hCom,&bytSendAddress,1,NULL,&m_osWrite);
for(int x=0;x<1000000;x++)
{
for(int y=0;y<2.5;y++){} // 延迟
}
GetCommState(m_hCom,&myDCB);
myDCB.Parity = SPACEPARITY;
fState=WriteFile(m_hCom,&bytSendData,length-1,NULL,&m_osWrite);
SetCommState(m_hCom,&myDCB);
fWriteAdr = true;
Sleep(iSleep);
if(!fState)
{
if (GetLastError()==ERROR_IO_PENDING)
{
GetOverlappedResult(m_hCom,&m_osWrite,&length,TRUE);//wait
}
}
接收数据:
DWORD length=0;
COMSTAT ComStat;
DWORD dwErrorFlags;
ClearCommError(m_hCom,&dwErrorFlags,&ComStat);
length=min(dwlength, ComStat.cbInQue);
ReadFile(m_hCom,&receiveLSControl,length,&length,&m_osRead);//receiveLSControl byte数组
关闭串口:
CloseHandle(m_hCom);