串口写入和读取数据
SerialPort类
WriteComm 写串口函数
DWORD CSerialPort::WriteComm(char *buf, DWORD dwLength) { if(!IsOpen()) { return 0; } assert(buf != NULL); COMSTAT comStat; DWORD dwErrorFlags; if (!ClearCommError(m_hCom, &dwErrorFlags, &comStat) && dwErrorFlags > 0) { PurgeComm(m_hCom, PURGE_TXABORT | PURGE_TXCLEAR); } OVERLAPPED osWrite; memset(&osWrite, 0, sizeof(OVERLAPPED)); osWrite.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); BOOL bWriteStat = WriteFile(m_hCom, buf, dwLength, &dwLength, &osWrite); if(!bWriteStat) { if(GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(osWrite.hEvent, 2000); } else { dwLength = 0; } } return dwLength; }
调用
char buf[10]; //字符数组 将字符串通过 strcpy 放入字符数组再向串口写入 strcpy(buf,"1234"); m_SerialPort.WriteComm(buf,4); MessageBox(_T("1234")); buf[0]=0x61; //将要发送的字符串或十六进制数据储存在char型字符数组中,利用WriteComm发送到串口 m_SerialPort.WriteComm(buf,1);
ReadComm
DWORD CSerialPort::ReadComm(char *buf, DWORD dwLength) { if(!IsOpen()) { return 0; } buf[0] = '\0'; COMSTAT comStat; DWORD dwErrorFlags; if (!ClearCommError(m_hCom, &dwErrorFlags, &comStat) && dwErrorFlags > 0) { PurgeComm(m_hCom, PURGE_RXABORT | PURGE_RXCLEAR); return 0; } if(comStat.cbInQue == 0) { return 0; } DWORD dwBytesRead=0; BOOL bReadStat; dwBytesRead = min(dwLength - 1, (DWORD)comStat.cbInQue); OVERLAPPED osRead; memset(&osRead,0,sizeof(OVERLAPPED)); osRead.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); DWORD dwByteOfRead = 0; bReadStat = ReadFile(m_hCom, buf, dwBytesRead, &dwByteOfRead, &osRead); if(!bReadStat) { if(GetLastError() == ERROR_IO_PENDING) { WaitForSingleObject(osRead.hEvent, 2000); // GetOverlappedResult(m_hCom, &osRead, &dwByteOfRead, FALSE) ; } } // PurgeComm(m_hCom, PURGE_TXABORT|PURGE_RXABORT|PURGE_TXCLEAR|PURGE_RXCLEAR); ////清空串口的接收缓冲区,必要性不大,但有保证作用?清空的话如果大数据会丢失 buf[dwByteOfRead] = '\0'; return dwByteOfRead; }
调用
char *pBuf=new char[10]; //定义一个char型字符数组,动态分配内存 memset(pBuf,0,10); m_SerialPort.ReadComm(pBuf,10);