16,473
社区成员
发帖
与我相关
我的任务
分享
void CMyComDlg::OpenPort(int nBaud, int nParity, int nDataBits, int nStopBits)
{
if(NULL != hPort)
hPort = CreateFile("COM1:",GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if (hPort == INVALID_HANDLE_VALUE)
{
AfxMessageBox(TEXT("Cannot open the port."));
}
else
{
SetCommMask (hPort, EV_RXCHAR|EV_TXEMPTY);
COMMTIMEOUTS timeout;
timeout.ReadIntervalTimeout = 10;
timeout.ReadTotalTimeoutConstant = 20;
timeout.ReadTotalTimeoutMultiplier = 100;
timeout.WriteTotalTimeoutConstant = 0;
timeout.WriteTotalTimeoutMultiplier = 0;
SetCommTimeouts(hPort,&timeout);
DCB PortDCB;
PortDCB.DCBlength = sizeof(DCB);
GetCommState (hPort, &PortDCB);
PortDCB.BaudRate=nBaud; // 串口BaudRate
PortDCB.ByteSize=nDataBits;
PortDCB.fRtsControl=0x00;
PortDCB.fBinary = true;
PortDCB.Parity = nParity; // 无奇偶校验,NOPARITY
PortDCB.StopBits = nStopBits;
SetCommState(hPort, &PortDCB);
SetupComm(hPort, 1024, 1);
//PurgeComm(hPort, PURGE_TXCLEAR | PURGE_RXCLEAR);
PurgeComm( hPort, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR| PURGE_RXCLEAR);
}
}