zoukankan      html  css  js  c++  java
  • 串口类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(); 

    作者:wqvbjhc
    出处:https://www.cnblogs.com/wqvbjhc/
    版权:本文版权归作者和博客园共有
    转载:欢迎转载,但未经作者同意,必须保留此段声明;必须在文章中给出原文连接;否则必究法律责任
  • 相关阅读:
    C语言II博客作业04
    C语言II博客作业03
    C语言II博客作业01
    学期总结
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业06
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业03
  • 原文地址:https://www.cnblogs.com/wqvbjhc/p/2465093.html
Copyright © 2011-2022 走看看