⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 unit1.cpp

📁 启用数据帧识别功能可使收到的数据永远是完整的每帧数据! 单片机开发者再也不用为数据帧首尾识别而烦恼了! 1.支持二进制数据和文本数据的收发 2.支持任意格式的数据的收发 3.支持两种数据包
💻 CPP
字号:
//---------------------------------------------------------------------------

#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);
   }
}
//---------------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -