原创 串口控件SPComm多方法使用例程

2006-12-28 22:57 6920 12 12 分类: 工业电子

点击下载:zip.gifspcommdemo.rar


重点注意:本例程一定要将串口的2,3脚短联做自发自收演示)


procedure TForm1.Button1Click(Sender: TObject);
var
  i: integer;
  str: string;
begin
  str := '';
  for i := 0 to 2047 do
  begin
    str := str + Char(i and $ff);//所有字符0x00~0xff
  end;
  Comm1.PortOpen := true;//打开串口(注意:本例将串口的2,3脚短联做自发自收演示)
  Comm1.Output := str;//发送2048个字符到串口
end;


procedure TForm1.Comm1ReceiveData(Sender: TObject; Buffer: PAnsiChar;//旧事件处理方法用Buffer: Pointer
  BufferLength: Word);
var
  i: integer;
  str: string;
begin                                      


  Memo1.Lines.Add('SPCOMM控件改造应用方法一:(String)');
  SetString(str, Buffer, BufferLength);//从串口接收BufferLength个字节
  if Length(str) <> BufferLength then Exit;
  for i := 0 to BufferLength - 1 do
  begin
    if (i and $f) = 0 then
    begin
      Buffers := inttohex(i, 4) + ': ';
    end;
    if (i and $ff) = Byte(str[i + 1]) then//str从str[1]开始
      Buffers := Buffers + '0x' + inttohex(Byte(str[i + 1]), 2) + ' '
    else //接收错误显示
      Buffers := Buffers + '**/' + inttohex(Byte(str[i + 1]), 2) + ' ';
    if (i and $f) = $f then
    begin
      Memo1.Lines.Add(Buffers);//输出一行显示数据
      Buffers := '';
    end;
  end;


  Memo1.Lines.Add('');
  Memo1.Lines.Add('SPCOMM控件改造应用方法二:(Array)');
  for i := 0 to BufferLength - 1 do
  begin
    if (i and $f) = 0 then
    begin
      Buffers := inttohex(i, 4) + ': ';
    end;
    if (i and $ff) = Byte(Buffer) then//Buffer从Buffer[0]开始
      Buffers := Buffers + '0x' + inttohex(Byte(Buffer), 2) + ' '
    else //接收错误显示
      Buffers := Buffers + '**' + inttohex(Byte(Buffer), 2) + ' ';
    if (i and $f) = $f then
    begin
      Memo1.Lines.Add(Buffers);//输出一行显示数据
      Buffers := '';
    end;
  end;


  Memo1.Lines.Add('');
  Memo1.Lines.Add('SPCOMM控件改造应用方法三:(Pointer)');
  for i := 0 to BufferLength - 1 do
  begin
    if (i and $f) = 0 then
    begin
      Buffers := inttohex(i, 4) + ': ';
    end;
    if (i and $ff) = Byte((Buffer + i)^) then//Buffer+i从Buffer开始
      Buffers := Buffers + '0x' + inttohex(Byte((Buffer + i)^), 2) + ' '
    else //接收错误显示
      Buffers := Buffers + '**' + inttohex(Byte((Buffer + i)^), 2) + ' ';
    if (i and $f) = $f then
    begin
      Memo1.Lines.Add(Buffers);//输出一行显示数据
      Buffers := '';
    end;
  end;


  Memo1.Lines.Add('');
  Memo1.Lines.Add('SPCOMM控件改造应用方法四:(Pointer)');
  for i := 0 to BufferLength - 1 do
  begin
    if (i and $f) = 0 then
    begin
      Buffers := inttohex(i, 4) + ': ';
    end;
    if (i and $ff) = Byte(Buffer^) then
      Buffers := Buffers + '0x' + inttohex(Byte(Buffer^), 2) + ' '
    else //接收错误显示
      Buffers := Buffers + '**' + inttohex(Byte(Buffer^), 2) + ' ';
    if (i and $f) = $f then
    begin
      Memo1.Lines.Add(Buffers);//输出一行显示数据
      Buffers := '';
    end;
    Inc(Buffer, SizeOf(Char));//移动字符指针
  end;


end;

PARTNER CONTENT

文章评论0条评论)

登录后参与讨论
EE直播间
更多
我要评论
0
12
关闭 站长推荐上一条 /3 下一条