串口類CSerialPort的簡單用法

簡單用法:

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(); 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章