码迷,mamicode.com
首页 > 其他好文 > 详细

一个串口类CSerialPort及其简单使用

时间:2016-05-14 00:59:10      阅读:1428      评论:0      收藏:0      [点我收藏+]

标签:

一个挺好用的串口类: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及其简单使用

标签:

原文地址:http://www.cnblogs.com/dgx/p/5491490.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!