一个挺好用的串口类:CnComm1.3。SerialPort.rar

简单用法:

1.定义成员:  
    CSerialPort m_SerialPort;  
      
2.初始化:  
 m_SerialPort.SetBufferSize(1024,1024); 
 m_SerialPort.SetWnd(m_hWnd);
 m_SerialPort.SetNotifyNum(DEF_IN_BYTE_SIZE);
 if (m_SerialPort.IsOpen())
 { 
  m_SerialPort.Close();
 } 
 m_SerialPort.Open(1,"9600,O,8,1");

 m_SerialPort.ClearInputBuffer(); 
 m_SerialPort.ClearOutputBuffer();
      
3.接收数据:  
    a.ON_MESSAGE(ON_COM_RECEIVE, RS232OnReceive)  
      
    b.RS232OnReceive函数体:  
 }m_SerialPort.Lock();

byte _RxData_Array[DEF_IN_BYTE_SIZE];
ZeroMemory(_RxData_Array,DEF_IN_BYTE_SIZE);
int nReceivedLength=0;

byte TempByte[DEF_IN_BYTE_SIZE];
ZeroMemory(TempByte,DEF_IN_BYTE_SIZE);
int _BufferLength=0;

// BOOL bFound0x51=FALSE;//数据头是否到来
DWORD _TickCount=GetTickCount();
while (nReceivedLength<DEF_IN_BYTE_SIZE)
{
 if ((GetTickCount()-_TickCount)>50)//防止接收不到数据的死循环
 {
  TRACE("接收数据超时.\n");
  break;
 

 _BufferLength=m_SerialPort.Read(TempByte,1);
//  if (!bFound0x51)//若还没有得到数据头
//  {
//   if (TempByte[0]==0x51)//判断数据头是否到来
//   {
//    bFound0x51=TRUE;
//   }
//  }
//
//  if (!bFound0x51)
//  {
//   TRACE("0x%02X:等待数据头到来.\n",TempByte[0]);
//   continue;
//  }

 if (_BufferLength>0)
 {
  memcpy(_RxData_Array+nReceivedLength,TempByte,_BufferLength);
  nReceivedLength+=_BufferLength; 
 }
}

m_SerialPort.ClearInputBuffer();
m_SerialPort.Unlock(); 
        
4.发送数据:  
    m_SerialPort.Lock();  
    m_SerialPort.Write(TxBuffer,9);  
    m_SerialPort.Unlock(); 

该类的作者博客:http://blog.csdn.net/wujian53/ (llbird的C/C++世界)
CnComm已经升级到了1.5。
http://blog.csdn.net/wujian53/archive/2009/04/18/4090685.aspx
CnComm1.5.zip


本文链接地址: 一个串口类CSerialPort及其简单使用
https://blog.qingfengju.com/index.asp?id=25

上一篇: 用VBScript编程控制Photoshop自动处理批量图片
下一篇: VC++中查找内存泄漏最简单的方法

分类:Win32/C++ 查看次数:19420 发布时间:2009/5/15 18:12:26