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] = '