//输入参数:波特率,数据位,停止位,校验位 //返回类型:无
void OpenComm(int nBaud, int nData, int nStop, int nCal) { hCom = CreateFile ( strcomname, //串口号 GENERIC_READ | GENERIC_WRITE, //允许读或写 0, //独占方式 NULL, OPEN_EXISTING, //打开而不是创建 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED,//重叠方式,用于异步通信 NULL ); if(hCom == INVALID_HANDLE_VALUE) { AfxMessageBox(\打开COM失败,串口不存在或已被占用!\ ComIsOK = false; return; } ComIsOK = true; SetCommMask(hCom, EV_TXEMPTY | EV_RXCHAR ); //设置事件掩码,暂时没用上 SetupComm(hCom,1024,1024); //设置输入缓冲区和输出缓冲区的大小都是1024 COMMTIMEOUTS TimeOuts; //设定读超时 TimeOuts.ReadIntervalTimeout = MAXDWORD; TimeOuts.ReadTotalTimeoutConstant = 0; TimeOuts.ReadTotalTimeoutMultiplier = 0; //设定写超时 TimeOuts.WriteTotalTimeoutConstant = 500; TimeOuts.WriteTotalTimeoutMultiplier = 100; if(SetCommTimeouts(hCom,&TimeOuts) == false) { CloseHandle(hCom); ComIsOK = false; return; } //串口属性配置 DCB dcb; GetCommState(hCom,&dcb); dcb.BaudRate=nBaud; //dcb.BaudRate=9600; //波特率为9600 dcb.ByteSize=nData; //dcb.ByteSize=8; //每个字节为8位 dcb.StopBits=nStop; //dcb.StopBits=ONESTOPBIT; //1位停止位 dcb.Parity=nCal; //dcb.Parity=NOPARITY; //无奇偶检验位
第 17 页 共 39 页
SetCommState(hCom,&dcb); PurgeComm(hCom,PURGE_TXCLEAR|PURGE_RXCLEAR); if(SetCommState(hCom,&dcb) == false) { CloseHandle(hCom); ComIsOK = false; return; } return; }
//==========串口打开函数结束=====================
//==========串口关闭控制函数===================== void CloseComm() { CloseHandle(hCom); hCom = NULL; ComIsOK = false; }
//==========串口关闭控制函数结束==================
//==========串口监听线程函数====================== UINT ThreadFunc(LPVOID pParam) {
// CCommassistDlg* pdlg = (CCommassistDlg*)pParam; //定义指针指向主对话框 COMSTAT ComStat; DWORD dwErrorFlags; while(ComIsOK) { DWORD dwBytesRead = 100; ClearCommError(hCom,&dwErrorFlags,&ComStat); dwBytesRead = min(dwBytesRead,(DWORD)ComStat.cbInQue); if(!dwBytesRead) { Sleep(10);//continue;//使用continue时,打开串口后CPU占用率非常高 } else ::SendMessage(::AfxGetMainWnd()->m_hWnd,WM_READCOMM,1,0); //发送消息,已读到 } return 0; }
//==========串口监听线程函数结束================
第 18 页 共 39 页
//=================字符串转16进制显示========== //字符串转16进制显示的函数 //传入参数Data为字符串
//Blank_allow为空格允许标志,为真则代表允许加入空格 //函数返回为CString的结果sResult
CString DisplayCString2Hex(CString Data, bool Blank_allow) { CString sResult; CString sTemp; int Data_Length; Data_Length = Data.GetLength(); if (Data_Length == 0) return \ char *pchar = new char[Data_Length]; //用了new分配内存空间,要记得释放 strncpy(pchar,Data,Data_Length); for(int i=0; i //===============函数结束============================ //=================16进制转字符串====================== //16进制转字符串,输入16进制的字符串,输出转换为16进制码 //传入参数str为字符串,判断输入是否按照16进制格式输入 int ConvertHexC2String(CString str, CByteArray &senddata) { //先判断输入字符串是否2个字符一组 int str_Length,iLength; int hexdata, l_data; char hstr,lstr; char cTemp; str_Length = str.GetLength(); iLength = 0; senddata.SetSize(str_Length/2); //预先设置数组长度,不设置时,允许有错 char *ppchar = new char[str_Length]; 第 19 页 共 39 页 strncpy(ppchar,str,str_Length); for(int i=0; i 第 20 页 共 39 页
相关推荐: