看看下面这个例子,传输数据流的程序;
unit FComm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SPComm, Spin;
type
TF_comm = class(TForm)
Comm1: TComm;
Memo1: TMemo;
Btn_Send: TButton;
Btn_exit: TButton;
Btn_send1: TButton;
Btn_Send2: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Comm1ReceiveData(Sender: TObject; Buffer: Pointer;BufferLength: Word);
procedure Btn_SendClick(Sender: TObject);
procedure Btn_exitClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Btn_send1Click(Sender: TObject);
procedure Btn_Send2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
F_comm: TF_comm;
Viewstring : string;
i:integer;
rbuf,sbuf:array[1..2] of byte;
rP:^integer;
commflg:boolean;
implementation
{$R *.DFM}
{打开串口}
procedure TF_comm.FormCreate(Sender: TObject);
begin
comm1.StartComm;
end;
{关闭串口}
procedure TF_COMM.FormClose(Sender: TObject; var Action: TCloseAction);
begin
comm1.StopComm;
end;
{发送数据 }
procedure SendData;
var
i:integer;
begin
viewstring:=' ';
commflg:=true;
for i:=1 to 2 do begin
if not F_Comm.comm1.writecommdata(@sbuf,1) then
begin
commflg:=false;
break;
end;
sleep(2); {发送时字节间的延时}
viewstring:=viewstring+inttohex(sbuf,2)+' ';
end;
viewstring:='发送'+viewstring;
F_Comm.memo1.lines.add(viewstring);
F_Comm.memo1.lines.add(');
if not commflg then messagedlg('发送失败!',mterror,[mbyes],0);
end;
{接收过程}
procedure TF_COMM.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;BufferLength: Word);
var
i:integer;
begin
viewstring :=';
rP := @rbuf;
move(buffer^,pchar(rP^),bufferlength);
for i:=1 to bufferlength do begin
viewstring :=viewstring+inttohex(rbuf,2)+';
end;
viewstring:='接受'+viewstring;
memo1.lines.add(viewstring);
memo1.lines.add(');
end;
procedure TF_comm.Btn_exitClick(Sender: TObject);
begin
{ comm1.StopComm; }
F_comm.Close;
end;
procedure TF_comm.Btn_send1Click(Sender: TObject);
begin
sbuf[1]:=byte($01); {地址}
sbuf[2]:=byte($0A); {结束符}
senddata;{调用发送函数}
end;
procedure TF_comm.Btn_Send2Click(Sender: TObject);
begin
sbuf[1]:=byte($02); {地址}
sbuf[2]:=byte($0A); {结束符}
senddata;{调用发送函数}
end;
procedure TF_COMM.Btn_sendClick(Sender: TObject);{发送按钮的点击事件}
begin
Btn_send1Click(Sender);
Sleep(300);
Btn_send2Click(Sender);
end;