二进制数据收发

来源:互联网 发布:花与爱丽丝杀人 知乎 编辑:程序博客网 时间:2024/05/20 20:04

串口通讯程序在大部分情况下都采用二进制数据收发
利用 Read 和 Write 方法, 可发送和接收任意类型的数据。

例(1), 发送简单数据类型:

char a[10];
AnsiString s;
short n;

YbCommDevice1->Write(a,10); //发送字符数组
YbCommDevice1->Write(s.c_str(),s.Length()); //发送字符串
YbCommDevice1->Write(&n,2); //发送一个 16 位的短整数, 先发送低位字节, 后发送高位字节


例(2), 发送结构:

#pragma pack(push,1) //用字节型对齐方式,下面的 TMyStruct 结构是 7 个字节, 否则 TMyStruct 结构是8个字节
typedef struct
{
char a; //字节型变量, 1 个字节
short b; //短整数变量, 2 个字节
long c; //长整数变量, 4 个字节
} TMyStruct;
#pragma pack(pop) //恢复原来的对齐方式

TMyStruct MyStruct; //定义结构变量
YbCommDevice1->Write(&MyStruct,sizeof(TMyStruct));


例(3), 接收数据:

char Buffer[8192]; //定义一个 8kb 缓存
int n = YbCommDevice1->Read(Buffer,8192); //收到 n 个字节, 接收的数据保存到 Buffer 里


例(4), 完整的例子:

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
    try
    {
        YbCommDevice1->PortNo = 1; //COM1
        YbCommDevice1->Active = true;
    }
    catch(Exception &e)
    {
        ShowMessage("YbCommDevice1: "+e.Message);
    }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSet1Click(TObject *Sender)
{
    YbCommDevice1->SettingsDialog(this,true);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ButtonSend1Click(TObject *Sender)
{
    int nBytes = 0;
    char Buffer[1000], *EndPtr;
    AnsiString t,s = Edit1->Text.Trim();
    while(s.Length()>0)
    {
        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->Write(Buffer,nBytes);
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
    unsigned char Buf[8192]; //收到的字节数不会超过串口缓存的容量, 所以分配一个缓存容量相同的Buf
    int n = YbCommDevice1->Read(Buf,8192); //收到 n 个字节
    AnsiString s;

    for(int i=0; i<n; i++)
        s += IntToHex(Buf[i],2) + " ";
    s = s.Trim();

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

原创粉丝点击