unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, SPComm, StdCtrls;
type
TForm1 = class(TForm)
Comm1: TComm;
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
procedure senddata;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
procedure Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
viewstring:string;
i:integer;
rbuf,sbuf:array[1..6] of byte;
implementation
{$R *.dfm}
procedure TForm1.FormShow(Sender: TObject);
begin
Comm1.StartComm;
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Comm1.StopComm;
end;
procedure TForm1.senddata;
var
i:integer;
commflg:boolean;
begin
viewstring:='' ;
commflg:=true;
for i:=1 to 6 do
begin
if not Form1.comm1.writecommdata(@sbuf,1) then
begin
commflg:=false;
break;
end;
//发送时字节间的延时
sleep(2);
viewstring:=viewstring+ inttohex(sbuf,2)+'';
end;
viewstring:='发送'+ viewstring;
Form1.memo1.lines.add(viewstring);
Form1.memo1.lines.add('');
if not commflg then messagedlg('发送失败 !',mterror,[mbyes],0);
end;
procedure TForm1.Button1Click(Sender: TObject);//发送
begin
sbuf[1]:=byte($f0); //帧头
sbuf[2]:=byte($01); //命令号
sbuf[3]:=byte($ff);
sbuf[4]:=byte($ff);
sbuf[5]:=byte($01);
sbuf[6]:=byte($f0); //帧尾
senddata;//调用发送函数
end;
//接收
procedure TForm1.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);
var
i:integer;
begin
viewstring:='';
move(buffer^,pchar(@rbuf)^,bufferlength);
for i:=1 to bufferlength do
viewstring:=viewstring+ inttohex(rbuf,2)+'';
viewstring:='接收'+ viewstring;
memo1.lines.add(viewstring);
memo1.lines.add('');
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
close;
end;
end.
我试过了,还可以