<%@Language=VBScript%> C++爱好者

 

Victor 控件使用方法详解 - TYbCommDevice

使用超时的方法接收数据包──适合与单片机通讯的协议

大部分情况与单片机通讯都使用超时的方法判断命令或数据包的开始和结束。
利用 ReadPackage 和 WritePackage 方法, 可发送和接收任意类型的数据。
可以在定时器、OnPackage事件、及程序任何想接收数据的地方接收数据。

完整的例子:

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "YbCommDevice"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
  try
   {
     YbCommDevice1->Active = true;
   }
  catch(Exception &e)
   {
     ShowMessage("YbCommDevice1: "+e.Message);
     if(!YbCommDevice1->SettingsDialog(this,true))
        Application->Terminate();
   }

  YbCommDevice1->PackageSize = 4096; //最大可发送 4096 个字节的数据包
  YbCommDevice1->PackageType = cptFrameTimeout; //用判断超时的方法接收数据包
  YbCommDevice1->UsePackage = true; //启动数据包 (可以随时启动和停止, 与 Active 属性无关)
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSetClick(TObject *Sender)
{
  YbCommDevice1->SettingsDialog(this,true);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSendClick(TObject *Sender)
{
  const BufSize = 4096;
  char Buffer[BufSize];
  int nBytes = 0;
  char *EndPtr=0; //指示数据转换错误 if(EndPtr){if(*EndPtr){ 转换失败 }}

  AnsiString t,s = Edit1->Text.Trim();
  while((s.Length()>0) && (nBytes<BufSize))
   {
     int p = s.Pos(' '); //空格
     if(p>0)
      {
        t = s.SubString(1,p-1);
        s = s.SubString(p+1,s.Length()).Trim();
        Buffer[nBytes++] = strtol(t.c_str(), &EndPtr, 16); //十六进制字符串转成字节
      }
     else //还剩下最后一个字节
      {
        t = s;
        s = "";
        Buffer[nBytes++] = strtol(t.c_str(), &EndPtr, 16); //十六进制字符串转成字节
      }
   }

  YbCommDevice1->WritePackage(Buffer,nBytes); //发送数据包
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
  const BufSize = 4096;
  unsigned char Buffer[BufSize];
  int nBytes = 0;
  while((nBytes=YbCommDevice1->ReadPackage(Buffer,BufSize))>0)
   {
     AnsiString s;
     for(int i=0; i<nBytes; i++)
     s += IntToHex(Buffer[i],2) + " ";
     s = s.Trim();

     if(!s.IsEmpty())
        Memo1->Lines->Add(s);
   }
}
//---------------------------------------------------------------------------

返回 TYbCommDevice

C++ 爱好者
-- Victor Chen 的个人主页
网址: http://www.cppfans.com/
Email: victor@cppfans.com
本站可以互相交换相关内容网站的链接
本站拒绝任何毫无相关的广告和链接