您好,欢迎访问三七文档
当前位置:首页 > 电子/通信 > 综合/其它 > C语言串口通信助手代码
该程序全部由C写成没有C++更没用MFC完全是自娱自乐给需要的人一个参考#includestdafx.h#includewindowsx.h#includeresource.h#includeMainDlg.h#includewindows.h#includestdio.h#includestdlib.hHANDLEhComm;//用于获取串口打开函数的返回值(句柄或错误值)OVERLAPPEDm_ov;COMSTATcomstat;DWORDm_dwCommEvents;TCHARcRecs[200],cSends[100];//接收字符串发送字符串charj=0,*cCom;//接收用统计数据大小变量端口选择BOOLWINAPIMain_Proc(HWNDhWnd,UINTuMsg,WPARAMwParam,LPARAMlParam){switch(uMsg){HANDLE_MSG(hWnd,WM_INITDIALOG,Main_OnInitDialog);HANDLE_MSG(hWnd,WM_COMMAND,Main_OnCommand);HANDLE_MSG(hWnd,WM_CLOSE,Main_OnClose);}returnFALSE;}/*系统初始化函数*/BOOLMain_OnInitDialog(HWNDhwnd,HWNDhwndFocus,LPARAMlParam){HWNDhwndCombo1=GetDlgItem(hwnd,IDC_COMBO1);ComboBox_InsertString(hwndCombo1,-1,TEXT(COM1));ComboBox_InsertString(hwndCombo1,-1,TEXT(COM2));ComboBox_InsertString(hwndCombo1,-1,TEXT(COM3));ComboBox_InsertString(hwndCombo1,-1,TEXT(COM4));ComboBox_InsertString(hwndCombo1,-1,TEXT(COM5));ComboBox_SetCurSel(hwndCombo1,0);voidCALLBACKTimerProc(HWNDhwnd,UINTmessage,UINTiTimerID,DWORDdwTime);SetTimer(hwnd,1,1000,TimerProc);returnTRUE;}/*监视串口错误时使用的函数*/boolProcessErrorMessage(char*ErrorText){char*Temp=newchar[200];LPVOIDlpMsgBuf;FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),//Defaultlanguage(LPTSTR)&lpMsgBuf,0,NULL);sprintf(Temp,WARNING:%sFailedwiththefollowingerror:\n%s\nPort:%d\n,(char*)ErrorText,lpMsgBuf,com2);MessageBox(NULL,Temp,ApplicationError,MB_ICONSTOP);LocalFree(lpMsgBuf);delete[]Temp;returntrue;}boolopenport(char*portname)//打开串口{hComm=CreateFile(portname,//串口号“com1”“com2”调用方法:boolopen;open=openport(com2);GENERIC_READ|GENERIC_WRITE,//允许读写0,//通讯设备必须以独占方式打开0,//无安全属性OPEN_EXISTING,//通讯设备已存在FILE_FLAG_OVERLAPPED,//异步I/O0);//通讯设备不能用模板打开if(hComm==INVALID_HANDLE_VALUE)//如果被占用或是没有打开时返回的是这个错误代码{CloseHandle(hComm);returnFALSE;}elsereturntrue;}boolsetupdcb(intrate_arg)//设置port的属性{DCBdcb;intrate=rate_arg;memset(&dcb,0,sizeof(dcb));if(!GetCommState(hComm,&dcb))//获取当前DCB配置returnFALSE;//setDCBtoconfiguretheserialportdcb.DCBlength=sizeof(dcb);dcb.BaudRate=rate;dcb.Parity=NOPARITY;//奇偶校验值0~4分别对应无校验、奇校验、偶校验、校验置位、校验清零dcb.fParity=0;//为1的话激活奇偶校验检查dcb.StopBits=ONESTOPBIT;//停止位个数,0~2分别对应1位、1.5位、2位停止位dcb.ByteSize=8;//数据位数dcb.fOutxCtsFlow=0;dcb.fOutxDsrFlow=0;dcb.fDtrControl=DTR_CONTROL_DISABLE;dcb.fDsrSensitivity=0;dcb.fRtsControl=RTS_CONTROL_DISABLE;dcb.fOutX=0;dcb.fInX=0;dcb.fErrorChar=0;dcb.fBinary=1;dcb.fNull=0;dcb.fAbortOnError=0;dcb.wReserved=0;dcb.XonLim=2;dcb.XoffLim=4;dcb.XonChar=0x13;dcb.XoffChar=0x19;dcb.EvtChar=0;//setDCBif(!SetCommState(hComm,&dcb))returnfalse;elsereturntrue;}/*串口读取相关时间设置*/boolsetuptimeout(DWORDReadInterval,DWORDReadTotalMultiplier,DWORDReadTotalconstant,DWORDWriteTotalMultiplier,DWORDWriteTotalconstant){COMMTIMEOUTStimeouts;timeouts.ReadIntervalTimeout=ReadInterval;//读取两个字节间隔最大值mS如超过立即返回不再读取timeouts.ReadTotalTimeoutConstant=ReadTotalconstant;//如果同下面一个都为0则无论是否读到数据都返回//可以毫秒为单位指定一个乘数,该乘数用来计算读操作的总限时时间timeouts.ReadTotalTimeoutMultiplier=ReadTotalMultiplier;//以毫秒为单位指定一个常数,用于计算读操作的总限时时间0表示不限时timeouts.WriteTotalTimeoutConstant=WriteTotalconstant;//写操作延时同上timeouts.WriteTotalTimeoutMultiplier=WriteTotalMultiplier;if(!SetCommTimeouts(hComm,&timeouts))returnfalse;elsereturntrue;}intClearn()//清除buff中的内容并返回buff中现有数据量的大小并读取错误原因{DWORDdwError=0;DWORDBytesRead=0;ClearCommError(hComm,&dwError,&comstat);returncomstat.cbInQue;//返回buff中数据量}/*串口数据接收读取函数*/voidReceiveChar(){BOOLbRead=TRUE;BOOLbResult=TRUE;DWORDdwError=0;DWORDBytesRead=0;chari=0,n;charRXBuff;j=0;while(i-n){n=i;Sleep(10);bResult=ClearCommError(hComm,&dwError,&comstat);i=(char)comstat.cbInQue;}for(;i0;i--){if(bRead)bResult=ReadFile(hComm,//HandletoCOMMport&RXBuff,//RXBufferPointer1,//Readonebyte&BytesRead,//Storesnumberofbytesread&m_ov);//pointertothem_ovstructure//printf(%c,RXBuff);cRecs[j++]=(char)RXBuff;if(!bResult){switch(dwError=GetLastError()){caseERROR_IO_PENDING:{bRead=FALSE;break;}default:break;}}elsebRead=TRUE;//closeif(bRead)if(!bRead){bRead=TRUE;bResult=GetOverlappedResult(hComm,//HandletoCOMMport&m_ov,//Overlappedstructure&BytesRead,//StoresnumberofbytesreadTRUE);//Waitflag}}}boolWriteChar(char*m_szWriteBuffer,DWORDm_nToSend)//写字符的函数{BOOLbWrite=TRUE;BOOLbResult=TRUE;DWORDBytesSent=0;HANDLEm_hWriteEvent;ResetEvent(m_hWriteEvent);if(bWrite){m_ov.Offset=0;m_ov.OffsetHigh=0;//ClearbufferbResult=WriteFile(hComm,//HandletoCOMMPortm_szWriteBuffer,//Pointertomessagebufferincallingfinctionm_nToSend,//Lengthofmessagetosend&BytesSent,//Wheretostorethenumberofbytessent&m_ov);//Overlappedstructureif(!bResult){DWORDdwError=GetLastError();switch(dwError){caseERROR_IO_PENDING:{//continuetoGetOverlappedResults()BytesSent=0;bWrite=FALSE;break;}default://allothererrorcodesbreak;}}}//endif(bWrite)if(!bWrite){bWrite=TRUE;bResult=GetOverlappedResult(hComm,//HandletoCOMMport&m_ov,//Overlappedstructure&BytesSent,//StoresnumberofbytessentTRUE);//Waitflag//dealwiththeerrorcodeif(!bResult){printf(GetOverlappedResults()inWriteFile());}}//endif(!bWrite)//Verifythatthedatasizesendequalswhatwetri
本文标题:C语言串口通信助手代码
链接地址:https://www.777doc.com/doc-4194458 .html