一个实用的串口通信类_yida.doc_第1页
一个实用的串口通信类_yida.doc_第2页
一个实用的串口通信类_yida.doc_第3页
一个实用的串口通信类_yida.doc_第4页
一个实用的串口通信类_yida.doc_第5页
已阅读5页,还剩12页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

修改一下更好用-/*/* File Name(文件名): SaimIO.h: interface for the CSaimIO class.Author(作者): Wenjin Hu 胡文晋 (eg. Saimen Hu) Version(版本): 1.0Date(完成日期): 2000.10.10Description(介绍): 用于 COM 口的读写类,完成对COM 口的选取,COM口的初始化。对COM口的读写操作。typedef struct tagIOINFOHANDLE idComDev;BYTE bPort;BOOL fConnected,fXonXoff;BYTE bByteSize,bFlowCtrl,bParity,bStopBits;Dword dwBaudRate;OVERLAPPED osWrite,osRead;IOINFO; 配置串口通信的数据结构 HANDLE idComDev 为串口句柄BYTE bPort 为串口号BOOL fConnected 为是否连接BYTE bByteSize 为字节数BYTE bFlowCtrl 流量控制BYTE bParity 校检类型BYTE bStopBits 停止位Dword dwBaudRate 波特率OVERLAPPED osWrite,osRead 读写事件及时限*/*/ Flow control flags 流量控制类型/#define FC_DTRDSR 0x01#define FC_RTSCTS 0x02#define FC_XONXOFF 0x04/ ascii definitions 流量控制字符/#define ASCII_XON 0x11#define ASCII_XOFF 0x13typedef struct tagIOINFOHANDLE idComDev;BYTE bPort;BOOL fConnected,fXonXoff;BYTE bByteSize,bFlowCtrl,bParity,bStopBits;Dword dwBaudRate;OVERLAPPED osWrite,osRead;IOINFO;/#if !defined(AFX_SAIMIO_H_A2648CC2_9DBF_11D4_96BD_E54AFA740DAA_INCLUDED_)#define AFX_SAIMIO_H_A2648CC2_9DBF_11D4_96BD_E54AFA740DAA_INCLUDED_#if _MSC_VER 1000#pragma once#endif / _MSC_VER 1000#define MSG_NEW_IODATA WM_USER+100class CSaimIO : public CFile public:CSaimIO();virtual CSaimIO();public:void ResumeThread();void SuspandThread();BOOL ConnectCom(LPTSTR initStr);BOOL EndListern();BOOL BeginListen();void ClearIObuffer();CString HexToStr(unsigned char *lpDataBuffer,int Total);void StrToHex(unsigned char *lpBuffer,int *Total);void InitaiseIO();void SetIO(IOINFO SetIoInfo);BOOL DisConnect();DWORD GetData(unsigned char *DataBuffer,Dword DataLength);BOOL SendData(unsigned char *lpCommand,Dword CmdLength);BOOL Connect();IOINFO IoInfoData;protected:/ 监听线程数据private:BOOL ThreadIsRun();HANDLE hListenThread;Dword dwThreadID;/ Dword WINAPI ListenThread(LPVOID lpParameter);/ 监听线程Dword WINAPI ListenThread(LPVOID lpParameter);#endif / !defined(AFX_SAIMIO_H_A2648CC2_9DBF_11D4_96BD_E54AFA740DAA_INCLUDED_)-/*/* File Name(文件名): SaimIO.cpp: implementation of the CSaimIO class.Author(作者): Wenjin Hu 胡文晋 (eg. Saimen Hu) Version(版本): 1.0Date(完成日期): 2000.10.10Description(介绍): 用于 COM 口的读写类,完成对COM 口的选取,COM口的初始化。对COM口的读写操作。Other(其它备注): 完成对串口的读写有两种情况:1.计算机之间通信2.计算您正在看的VC是:一个实用的串口通信类。 机和其它设备通信 对于这两种情况要注意在初始化COM的DCB结构时,成员不同的值对通信产后不同的效果,也许是非常严重的。例下面:如果把下面两个成员的值赋为以下情况dcb.fDtrControl = DTR_CONTROL_ENABLE ;dcb.fRtsControl = RTS_CONTROL_ENABLE ;此时不能完成计算机和其它设备之间通信。改为以下值就可以完成和其它设备能信。dcb.fDtrControl = DTR_CONTROL_DISABLE ;dcb.fRtsControl = RTS_CONTROL_ENABLE ;Funtion List(主要函数):1. void InitaiseIO() 用来对串口IOINFO 数据结构初始化为默认值2. void SetIO(IOINFO SetIoInfo)调用该函数用来修改IOINFO数据结构,配置串口说明:该函数在 CONNECT 之前调用。3. BOOL Connect() 用来连接串口,使用IOINFO中的数据结构,如果成功返回 TRUE;不成功返回 FALSE;4. BOOL DisConnect() 关闭对串口的连接,成功返回: TRUE 否则返回:FALSE5. BOOL SendData(unsigned char *lpCommand,Dword CmdLength)向串口发送数据,数据长度为 CmdLength,lpCommand 为指向该命令的指针。6. BOOL GetData(unsigned char *Databuffer,int DataLength)读取串口缓冲中的数据。History(修改记录):1.Date: 2000.10.11Author: 胡文晋 (EG. Saim Hu)Modification: 添加函数: CString CSaimIO:HexToStr(unsigned char *lpDataBuffer) 功 能: 将入口参数unsigned char * DataBuffer 转换为CString 字符串2.Date: 2000.11.10Author: 胡文晋 (EG. Saim Hu)Modifcation:*/*/#include stdafx.h#include SaimIO.h#ifdef _DEBUG#undef THIS_FILEstatic char THIS_FILE=_FILE_;#define new DEBUG_NEW#endifextern BOOL KillListenThread ;/ Construction/Destruction/CSaimIO:CSaimIO()InitaiseIO();hListenThread = NULL;CSaimIO:CSaimIO()/ 以默认方式初始化串口void CSaimIO:InitaiseIO()IoInfoData.idComDev = 0 ;IoInfoData.bByteSize = 8 ;IoInfoData.fConnected = FALSE; IoInfoData.bPort = 1 ;IoInfoData.dwBaudRate = CBR_4800;IoInfoData.bFlowCtrl = FALSE; /FC_XONXOFF; / FC_RTSCTS; /FC_XONXOFF;IoInfoData.bParity = EVENPARITY ; /MARKPARITY ; SPACEPARITY; ODDPARITY;IoInfoData.bStopBits = ONESTOPBIT; /ONE5STOPBITS; TWOSTOPBITSIoInfoData.osWrite.Offset = 0;IoInfoData.osWrite.OffsetHigh = 1024;IoInfoData.osRead.Offset = 0;IoInfoData.osRead.OffsetHigh = 1024;IoInfoData.osRead.hEvent = NULL;IoInfoData.osWrite.hEvent = NULL;/ 修改串口数据结构void CSaimIO:SetIO(IOINFO SetIoInfo)IoInfoData.idComDev = SetIoInfo.idComDev ;IoInfoData.bByteSize = SetIoInfo.bByteSize ;IoInfoData.fConnected = SetIoInfo.fConnected;IoInfoData.bPort = SetIoInfo.bPort ;IoInfoData.dwBaudRate = SetIoInfo.dwBaudRate;IoInfoData.bFlowCtrl = SetIoInfo.bFlowCtrl;IoInfoData.bParity = SetIoInfo.bParity;IoInfoData.bStopBits = SetIoInfo.bStopBits;IoInfoData.osWrite.Offset = SetIoInfo.osWrite.Offset;IoInfoData.osWrite.OffsetHigh = SetIoInfo.osWrite.OffsetHigh;IoInfoData.osRead.Offset = SetIoInfo.osRead.Offset;IoInfoData.osRead.OffsetHigh = SetIoInfo.osRead.OffsetHigh;/ Connect IO before use it./ 打开串开BOOL CSaimIO:Connect()BOOL fRetVal ;BYTE bSet ;DCB dcb ;char szPort;memset(szPort,0,10);wsprintf(szPort,COM%d:,IoInfoData.bPort);IoInfoData.idComDev = CreateFile(szPort,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,NULL);if( !IoInfoData.idComDev )return FALSE;if(!SetCommMask(IoInfoData.idComDev,EV_RXFLAG) / EV_RXCHAR)return FALSE;/ Alloc the buffer for Read and Write.if( SetupComm(IoInfoData.idComDev,4096,4096) = 0 )return FALSE;/Setup for overlapped I/OCOMMTIMEOUTS CommTimesOuts;CommTimesOuts.ReadIntervalTimeout = 100;CommTimesOuts.ReadTotalTimeoutMultiplier = 20; CommTimesOuts.ReadTotalTimeoutConstant = 1000 ;CommTimesOuts.WriteTotalTimeoutMultiplier = 2*CBR_9600 / IoInfoData.dwBaudRate ;CommTimesOuts.WriteTotalTimeoutConstant = 1000;SetCommTimeouts(IoInfoData.idComDev,&CommTimesOuts);/ Initise the com port.dcb.DCBlength = sizeof( DCB ) ;GetCommState( IoInfoData.idComDev, &dcb ) ;dcb.BaudRate = IoInfoData.dwBaudRate ;dcb.ByteSize = IoInfoData.bByteSize ;dcb.Parity = IoInfoData.bParity ;dcb.StopBits = IoInfoData.bStopBits ;/ setup hardware flow controlbSet = (BYTE) (FC_RTSCTS & FC_DTRDSR) != 0) ;dcb.fOutxDsrFlow = bSet ;dcb.fDtrControl = DTR_CONTROL_DISABLE ; /给予提供电源 , 新的 485 就不需要提供dcb.fRtsControl = RTS_CONTROL_ENABLE ;bSet = (BYTE) FC_RTSCTS ;dcb.fOutxCtsFlow = bSet ;/ setup software flow controlbSet = (BYTE) FC_XONXOFF ;dcb.fInX = dcb.fOutX = bSet ;dcb.XonChar = ASCII_XON ;dcb.XoffChar = ASCII_XOFF ;dcb.XonLim = 100 ;dcb.XoffLim = 100 ;/ other various settingsdcb.fBinary = TRUE ;dcb.fParity = 1 ; / Enalble ParityfRetVal = SetCommState( IoInfoData.idComDev, &dcb ) ;if( fRetVal != FALSE )IoInfoData.fConnected = TRUE;elsereturn fRetVal;/Ceate I/O event used for overlapped reads / writesIoInfoData.osRead.hEvent = CreateEvent( NULL , /no securityTRUE , /eXPlicit reset reqFALSE , /initial event resetNULL); /no nameif( IoInfoData.osRead.hEvent = NULL )return FALSE;IoInfoData.osWrite.hEvent = CreateEvent( NULL , /no securityTRUE , /eXPlicit reset reqFALSE , /initial event resetNULL); /no nameif( IoInfoData.osWrite.hEvent = NULL )CloseHandle( IoInfoData.osRead.hEvent );return FALSE;/ Clear Read and Send IO bufferif(PurgeComm(IoInfoData.idComDev,PURGE_RXCLEAR)= 0)return FALSE;if(PurgeComm(IoInfoData.idComDev,PURGE_TXCLEAR)= 0)return FALSE;/ Set The DataSet is ready TO Get DataEscapeCommFunction(IoInfoData.idComDev,SETDTR|SETRTS);/ set connected flag to TRUEIoInfoData.fConnected = TRUE ;return ( TRUE ) ;/ Close IO when exit the program./ 关闭串口BOOL CSaimIO:DisConnect()if(IoInfoData.fConnected = FALSE )return TRUE;/ Stop the Listen ThreadEndListern();/ set connected flag to FALSEIoInfoData.fConnected = FALSE ;/ disable event notification and wait for thread/ to haltSetCommMask( IoInfoData.idComDev , 0 ) ;/ drop DTREscapeCommFunction( IoInfoData.idComDev, CLRDTR | CLRRTS) ;/ purge any outstanding reads/writes and close device handleif(PurgeComm( IoInfoData.idComDev, PURGE_TXABORT | PURGE_RXABORT |PURGE_TXCLEAR | PURGE_RXCLEAR ) = 0 )return TRUE;CloseHandle(IoInfoData.osRead.hEvent);CloseHandle(IoInfoData.osWrite.hEvent);return CloseHandle( IoInfoData.idComDev ) ;/ Send the Datas./ 写数据到串口BOOL CSaimIO:SendData(unsigned char *lpCommand, Dword dwBytesToWrite)BOOL fWriteStat ;Dword dwBytesWritten ;Dword dwErrorFlags;Dword dwError;Dword dwBytesSent=0;COMSTAT ComStat;char szError 128 ;if (IoInfoData.fConnected = FALSE )return ( FALSE ) ;fWriteStat = WriteFile( IoInfoData.idComDev , lpCommand, dwBytesToWrite,&dwBytesWritten,NULL) ; / &IoInfoData.osWrite ) ;if(dwBytesWritten != dwBytesToWrite)return FALSE;if (!fWriteStat)if(GetLastError() = ERROR_IO_PENDING)while(!GetOverlappedResult( IoInfoData.idComDev ,&IoInfoData.osWrite, &dwBytesWritten, TRUE )dwError = GetLastError();if(dwError = ERROR_IO_INCOMPLETE)/ normal result if not finisheddwBytesSent += dwBytesWritten;continue;else/ an error occurred, try to recoverwsprintf( szError, 向串口发送数据出错,错误代码: %u, dwError ) ;MessageBox(NULL,szError,发送数据出错,MB_ICONEXCLAMATION);ClearCommError( IoInfoData.idComDev , &dwErrorFlags, &ComStat ) ;break;else/ some other error occurredClearCommError( IoInfoData.idComDev , &dwErrorFlags, &ComStat ) ;if (dwErrorFlags 0)wsprintf( szError, 向串口发送数据出错,错误代码: %u, dwErrorFlags ) ;MessageBox(NULL,szError,发送数据出错,MB_ICONEXCLAMATION);return ( FALSE );return ( TRUE ) ; / end of SendData()/ Read the Datas./ 从串口中读出数据DWORD CSaimIO:GetData(unsigned char *DataBuffer, Dword DataLength)BOOL fReadStat ;COMSTAT ComStat ;Dword dwErrorFlags;Dword dwLength = DataLength;Dword dwError;char szError 128 ;if (IoInfoData.fConnected = FALSE)return ( FALSE ) ;/ SetCommMask( IoInfoData.idComDev ,EV_RXCHAR) ; /设定为收到第一个字符时产生中断/ unsigned long dwFlg;/ WaitCommEvent(IoInfoData.idComDev , &dwFlg, &IoInfoData.osRead); /等侍收到第一个字符事件发生/ if( (dwFlg & ( EV_RXFLAG | EV_RXCHAR ) = (EV_RXFLAG | EV_RXCHAR) )/ only try to read number of bytes in queueClearCommError( IoInfoData.idComDev, &dwErrorFlags, &ComStat ) ;dwLength = min( 128, ComStat.cbInQue ) ;if (dwLength 0)fReadStat = ReadFile( IoInfoData.idComDev, DataBuffer,dwLength, &dwLength, &IoInfoData.osRead );if (!fReadStat)if (GetLastError() = ERROR_IO_PENDING)/ We have to wait for read to complete./ This function will timeout according to the/ CommTimeOuts.ReadTotalTimeoutConstant variable/ Every time it times out, check for port errorswhile(!GetOverlappedResult( IoInfoData.idComDev,&IoInfoData.osRead, &dwLength, TRUE )dwError = GetLastError();if(dwError = ERROR_IO_INCOMPLETE)/ normal result if not finishedcontinue;else/ an error occurred, try to recoverwsprintf( szError, 向串口发送数据出错,错误代码: %u, dwError ) ;MessageBox(NULL,szError,发送数据出错,MB_ICONEXCLAMATION);ClearCommError( IoInfoData.idComDev, &dwErrorFlags, &ComStat ) ;if (dwErrorFlags 0)wsprintf( szError, 向串口发送数据出错,错误代码: %u, dwError ) ;MessageBox(NULL,szError,发送数据出错,MB_ICONEXCLAMATION);break;else/ some other error occurreddwLength = 0 ;ClearCommError( IoInfoData.idComDev, &dwErrorFlags, &ComStat ) ;if (dwErrorFlagwsprintf( szError, 向串口发送数据出错,错误代码: %u, dwErrorFlags ) ;MessageBox(NULL,szError,发送数据出错,MB_ICONEXCLAMATION); return ( dwLength ) ;/ 把字符串转换为十六进制数据void CSaimIO:StrToHex(unsigned char *lpBuffer, int *Total)if(*Total) % 2) != 0)strcat(char *)lpBuffer,0);(*Total) +;unsigned char HexBuffer1024;memset(HexBuffer,0,1024);int i ;for( i = 0 ; i 0x39)lpBufferi -= 0x37 ;elselpBufferi -= 0x30 ;for(i=0 ; i (*Total) ; i+=2)HexBufferi/2 = lpBufferi ;HexBufferi/2 = 4;HexBufferi/2 |= lpBufferi+1;memcpy(lpBuffer,HexBuffer,(*Total)/2);/ 把十六进制数据转换为字符串CString CSaimIO:HexToStr(unsigned char *lpDataBuffer,int Total)CString ReturnStr;char OneNumber;ReturnStr.Empty();memset(OneNumber,0,5);for(int i=0;iTotal;i+)itoa(lpDataBufferi,OneNumber,16);if(strlen(OneNumber) 3) return FALSE;strTempj = 0;IoInfoData.bPort = atoi(strTemp);/ 读出波特率i+;j=0;while(initStri!=, & initStri != 0)strTempj = initStri;i+;j+;if(j 6) return FALSE;strTempj = 0;if(strstr(strTemp,256000) != NULL)IoInfoData.dwBaudRate = CBR_256000;else if(strstr(strTemp,128000) != NULL)IoInfoData.dwBaudRate = CBR_128000;else if(strstr(strTemp,115200) != NULL)IoInfoData.dwBaudRate = CBR_115200;else if(strstr(strTemp,57600) != NULL)IoInfoData.dwBaudRate = CBR_57600;else if(strstr(strTemp,56000) != NULL)IoInfoData.dwBaudRate = CBR_56000;else if(strstr(strTemp,38400) != NULL)IoInfoData.dwBaudRate = CBR_38400;else if(strstr(strTemp,19200) != NULL)IoInfoData.dwBaudRate = CBR_19200;else if(strstr(strTemp,14400) != NULL)IoInfoData.dwBaudRate = CBR_14400;else if(strstr(strTemp,9600) != NULL)IoInfoData.dwBaudRate = CBR_9600;else if(strstr(strTemp,4800) != NULL)IoInfoData.dwBaudRate = CBR_4800;else if(strstr(strTemp,2400) != NULL)IoInfoData.dwBaudRate = CBR_2400;else if(strstr(s

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论