下载
加入VIP
  • 专属下载特权
  • 现金文档折扣购买
  • VIP免费专区
  • 千万文档免费下载

上传资料

关闭

关闭

关闭

封号提示

内容

首页 WindowsXP windows2000下RS485通讯测试程序

WindowsXP windows2000下RS485通讯测试程序.doc

WindowsXP windows2000下RS485通讯测试…

吞噬玉瑞
2017-10-14 0人阅读 举报 0 0 暂无简介

简介:本文档为《WindowsXP windows2000下RS485通讯测试程序doc》,可适用于综合领域

WindowsXPwindows下RS通讯测试程序WindowsXP下RS通讯测试程序此测试程序为WindowsXP下的测试工具。操作说明:把COM,COM的设置成RS,。用短接线把的COM,COM连接好即COM的与COM的直接连接。进入系统,运行RSTestexe。选择要测试的COM口,工作模式CHANGECOMMODE:SENDORREAD(SORR)在这里选择是要发送还是接收。回车如果COM,COM出现相应的字符既表示这个串口工作正常。#include<stdioh>#include<stdlibh>#include<stringh>#include"Serialh"RS测试程序intRSTest(){unsignedintunComNum=unsignedintunComNum=unsignedcharucComMod=unsignedcharucComMod=charchCom={}CSerialserialCSerialserialcharbuffer={}longlSendCounter=charszSendBuff={}DWORDdwRead=inti===================输入COM的端口号和工作模式===========================fprintf(stdout,"nEnterCOMNumber(,):")scanf("d",unComNum)unComNum=fprintf(stdout,"ChangeCOMmode:SendorRead(sorr):")scanf("s",ucComMod)memset(chCom,,)sprintf(chCom,"COMd",unComNum)BOOLbSer=serialInitCOM(chCom,,,,,)if(!bSer){fprintf(stdout,"Can'tInitCOMComn")return}==================输入COM的端口号和工作模式===========================fprintf(stdout,"nEnterCOMNumber(,):")scanf("d",unComNum)unComNum=fprintf(stdout,"ChangeCOMmode:SendorRead(sorr):")scanf("s",ucComMod)memset(chCom,,)sprintf(chCom,"COMd",unComNum)bSer=serialInitCOM(chCom,,,,,)if(!bSer){fprintf(stdout,"Can'tInitCOMComn")return}fprintf(stdout,"InputSenddata:")scanf("s",szSendBuff)for(intk=k<k){if((ucComMod=='s')||(ucComMod=='S')){serialSendData(szSendBuff,strlen(szSendBuff))}if((ucComMod=='s')||(ucComMod=='S')){serialSendData(szSendBuff,strlen(szSendBuff))}Sleep()if((ucComMod=='r')||(ucComMod=='R')){memset(buffer,,sizeof(buffer))dwRead=serialReadData(buffer,sizeof(buffer))printf("COMk=d,ReceiveDataLen=d,Data(HEX):",k,dwRead)for(i=i<dwReadi){printf("x,",bufferi)}printf("n")}if((ucComMod=='r')||(ucComMod=='R')){memset(buffer,,sizeof(buffer))dwRead=serialReadData(buffer,sizeof(buffer))printf("COMk=d,ReceiveDataLen=d,Data(HEX):",k,dwRead)for(i=i<dwReadi){printf("x,",bufferi)}printf("n")}}serialClose()serialClose()return}intmain(intargc,char**argv){RSTest()return}Serialcpp:implementationoftheCSerialclass#include<winioctlh>#include<stdioh>#include<conioh>#include<stdlibh>#include"Serialh"ConstructionDestructionCSerial::CSerial(){memset(mOverlappedRead,,sizeof(OVERLAPPED))memset(mOverlappedWrite,,sizeof(OVERLAPPED))mhIDComDev=fWaitingOnRead=FALSE}CSerial::~CSerial(){Close()}************************************************************************RS通讯说明由于RS是半双工通信故同一时刻只能发送或接收。RS的发送与接收由串行口的RTS信号控制。一般在打开端口时需要将RTS设置为低以便该端口处于接收状态当该端口需要发送时需要将RTS置为高。*************************************************************************************************************************************************Function:初始化COM端口*Input:strPort:端口名称比如"COM"*nBaud:波特率比如*nByteSize:数据位比如*nParity:奇偶校验位,NOPARITY表示Noparity,EVENPARITY表示EvenMARKPARITY表示MarkODDPARITY表示OddSPACEPARITY表示Space*nStopBits:停止位,ONESTOPBIT表示stopbitONESTOPBITS表示stopbitsTWOSTOPBITS表示stopbits*iFlowControl:暂时不用*上面参数更详细的说明可参考MSDN。*Output:无*RetValue:成功返回TRUE失败返回FALSE*Author:xxxat::************************************************************************BOOLCSerial::InitCOM(constchar*strPort,intnBaud,BYTEnByteSize,BYTEnParity,BYTEnStopBits,intiFlowControl){DCBdcb={}如果已经打开串口则直接返回if(!((mhIDComDev==INVALIDHANDLEVALUE)||(mhIDComDev==))){returnTRUE}打开串口mhIDComDev=CreateFile(strPort,GENERICREAD|GENERICWRITE,,,OPENEXISTING,FILEATTRIBUTENORMAL|FILEFLAGOVERLAPPED,)if(mhIDComDev==INVALIDHANDLEVALUE){returnFALSE}memset(mOverlappedRead,,sizeof(OVERLAPPED))memset(mOverlappedWrite,,sizeof(OVERLAPPED))mOverlappedReadhEvent=CreateEvent(,TRUE,FALSE,)mOverlappedWritehEvent=CreateEvent(,TRUE,FALSE,)SetupComm(mhIDComDev,MAXREADBUFFER,MAXWRITEBUFFER)设置输入输出缓冲区设置通讯参数即设置波特率数据位停止位奇偶校验位dcbDCBlength=sizeof(DCB)GetCommState(mhIDComDev,dcb)dcbBaudRate=nBaudif(nByteSize<||nByteSize>){nByteSize=}dcbByteSize=nByteSizeif(nStopBits>){nStopBits=}dcbStopBits=nStopBitsif(nParity>){nParity=}dcbParity=nParity对dcb配置进行修改dcbfDtrControl=DTRCONTROLDISABLEdcbfRtsControl=RTSCONTROLDISABLEdcbfParity=TRUEdcbXonLim=dcbXoffLim=if(!SetCommState(mhIDComDev,dcb)||mOverlappedReadhEvent==||mOverlappedWritehEvent==){DWORDdwError=GetLastError()fprintf(stdout,"nerroratconnectn")printf("dwError=dn",dwError)returnFALSE}设置超时COMMTIMEOUTSCommTimeOutsCommTimeOutsReadIntervalTimeout=CommTimeOutsReadTotalTimeoutMultiplier=CommTimeOutsReadTotalTimeoutConstant=CommTimeOutsWriteTotalTimeoutMultiplier=CommTimeOutsWriteTotalTimeoutConstant=SetCommTimeouts(mhIDComDev,CommTimeOuts)*来自MSDNBOOLEscapeCommFunction(HANDLEhFile,handletocommunicationsdeviceDWORDdwFuncextendedfunctiontoperform)ParametershFileHandletothecommunicationsdeviceTheCreateFilefunctionreturnsthishandledwFuncSpecifiesthecodeoftheextendedfunctiontoperformThisparametercanbeoneofthefollowingvalues:ValueMeaningCLRDTRClearstheDTR(dataterminalready)signalCLRRTSClearstheRTS(requesttosend)signalSETDTRSendstheDTR(dataterminalready)signalSETRTSSendstheRTS(requesttosend)signalSETXOFFCausestransmissiontoactasifanXOFFcharacterhasbeenreceivedSETXONCausestransmissiontoactasifanXONcharacterhasbeenreceivedSETBREAKSuspendscharactertransmissionandplacesthetransmissionlineinabreakstateuntiltheClearCommBreakfunctioniscalled(orEscapeCommFunctioniscalledwiththeCLRBREAKextendedfunctioncode)TheSETBREAKextendedfunctioncodeisidenticaltotheSetCommBreakfunctionNotethatthisextendedfunctiondoesnotflushdatathathasnotbeentransmittedCLRBREAKRestorescharactertransmissionandplacesthetransmissionlineinanonbreakstateTheCLRBREAKextendedfunctioncodeisidenticaltotheClearCommBreakfunction*设置硬件流控,注意RTS初始化时设为低(SetRTSlow),即默认处于接收状态EscapeCommFunction(mhIDComDev,CLRRTS)if(!EscapeCommFunction(mhIDComDev,SETDTR)){returnFALSE}清空串口PurgeComm(mhIDComDev,PURGETXABORT|PURGERXABORT|PURGETXCLEAR|PURGERXCLEAR)returnTRUE}*************************************************************************Function:向串口发送数据*Input:pszBuf,发送数据缓冲区*nBufLen,发送数据长度*Output:无*RetValue:返回实际发送字节数*Author:************************************************************************intCSerial::SendData(constchar*pszBuf,intnBufLen){DWORDdwLastErrorDWORDdwNumberOfBytesWritten=DWORDdwWhereToStartWriting=DWORDdwNumberOfBytesToWrite=nBufLenDWORDdwHandleSignaled设置硬件流控,注意发送时RTS设为高(SetRTShigh)EscapeCommFunction(mhIDComDev,SETRTS)DWORDdwBytesWritten=if((mhIDComDev==INVALIDHANDLEVALUE)||(mhIDComDev==)){fprintf(stdout,"无效的串行口地址")return}do{发送数据if(!::WriteFile(mhIDComDev,pszBufdwWhereToStartWriting,dwNumberOfBytesToWrite,dwNumberOfBytesWritten,mOverlappedWrite)){dwLastError=GetLastError()if(dwLastError!=ERRORIOPENDING){fprintf(stdout,"串行口已关闭")return}dwHandleSignaled=WaitForSingleObject(mOverlappedWritehEvent,INFINITE)switch(dwHandleSignaled){caseWAITOBJECT:{break}caseWAITABANDONED:WaitfailedShouldn'thappen{return}default:Thiscaseshouldneveroccur{return}}if(!GetOverlappedResult(mhIDComDev,mOverlappedWrite,dwNumberOfBytesWritten,TRUE)){dwLastError=GetLastError()fprintf(stdout,"重叠查询结果失败")return}}dwNumberOfBytesToWrite=dwNumberOfBytesWrittendwWhereToStartWriting=dwNumberOfBytesWritten}while(dwNumberOfBytesToWrite>)returndwNumberOfBytesWritten}*************************************************************************Function:从串口接收数据*Input:buffer,接收数据缓冲区*dwReadLen,接收数据长度*Output:无*RetValue:返回实际读取数据长度*Author:************************************************************************intCSerial::ReadData(void*buffer,intdwReadLen){DWORDdwResult=BOOLbReadState=FALSEDWORDdwRealReadLen=实际读取字节数DWORDdwErrorFlags=COMSTATComStatEscapeCommFunction(mhIDComDev,CLRRTS)if((mhIDComDev==INVALIDHANDLEVALUE)||(mhIDComDev==))return解决空读情况下程序死掉的问题。原因:空读的话原来程序的线程会一直在等待读取字符,Addbyxxxat:ClearCommError(mhIDComDev,dwErrorFlags,ComStat)dwReadLen=min(dwReadLen,(DWORD)ComStatcbInQue)bReadState=ReadFile(mhIDComDev,buffer,dwReadLen,dwRealReadLen,mOverlappedRead)if(!bReadState)非表示失败表示成功{if(GetLastError()==ERRORIOPENDING){dwResult=WaitForSingleObject(mOverlappedReadhEvent,)switch(dwResult){caseWAITOBJECT:if(!GetOverlappedResult(mhIDComDev,mOverlappedRead,dwRealReadLen,FALSE)){if(GetLastError()==ERROROPERATIONABORTED){return}}else{if(dwRealReadLen)readcompletedsuccessfullyreturndwRealReadLen}breakcaseWAITTIMEOUT:returndefault:break}}}returndwRealReadLen}*************************************************************************Function:关闭打开的串口*Input:无*Output:无*RetValue:成功返回TRUE失败返回FALSE*Author:************************************************************************BOOLCSerial::Close(void){if(mOverlappedReadhEvent!=){CloseHandle(mOverlappedReadhEvent)mOverlappedReadhEvent=}if(mOverlappedWritehEvent!=){CloseHandle(mOverlappedWritehEvent)mOverlappedWritehEvent=}if(mhIDComDev==)returnTRUEelsereturnFALSECloseHandle(mhIDComDev)mhIDComDev=returnTRUE}Serialh:interfacefortheCSerialclass#if!defined(AFXSERIALHFCABBEFBAINCLUDED)#defineAFXSERIALHFCABBEFBAINCLUDED#ifMSCVER>#pragmaonce#endifMSCVER>#defineMAXREADBUFFER#defineMAXWRITEBUFFER#defineAMOUNTTOREAD#include<windowsh>#include<string>usingnamespacestdclassCSerial{public:CSerial()~CSerial()HANDLEmhIDComDevBOOLInitCOM(constchar*strPort="COM",intnBaud=,BYTEnByteSize=,BYTEnParity=,BYTEnStopBits=,intiFlowControl=)BOOLClose(void)intReadData(void*,int)intSendData(constchar*pszBuf,intnBufLen)BOOLIsOpened(void){if(mhIDComDev==)returnFALSEelsereturnTRUE}protected:OVERLAPPEDmOverlappedRead,mOverlappedWriteBOOLfWaitingOnRead}#endif!defined(AFXSERIALHFCABBEFBAINCLUDED)

用户评价(0)

关闭

新课改视野下建构高中语文教学实验成果报告(32KB)

抱歉,积分不足下载失败,请稍后再试!

提示

试读已结束,如需要继续阅读或者下载,敬请购买!

文档小程序码

使用微信“扫一扫”扫码寻找文档

1

打开微信

2

扫描小程序码

3

发布寻找信息

4

等待寻找结果

我知道了
评分:

/20

WindowsXP windows2000下RS485通讯测试程序

VIP

在线
客服

免费
邮箱

爱问共享资料服务号

扫描关注领取更多福利