用spcomm进行串口通讯,抄来一段程序,为何发送成功后不能接收。
lyq 2002-02-04 05:39:02 unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,StdCtrls, SPComm;
type
TForm1 = class(TForm)
Comm1: TComm;
Memo1: TMemo;
Button1: TButton;
procedure Comm1ReceiveData(Sender: TObject; Buffer: Pointer;BufferLength: Word);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
viewstring:string;
i:integer;
rbuf,sbuf:array[0..16] of byte;
implementation
{$R *.DFM}
procedure TForm1.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;BufferLength: Word);
var
s: string;
begin
SetLength(S, BufferLength); //接收RS232的数据并显示Memo1上。
Move(Buffer^, PChar(S)^, BufferLength);
Memo1.Lines.Add(S);
Memo1.Invalidate;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Comm1.startcomm;//创建窗体时,将comm1控件打开。
end;
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
comm1.StopComm;//关闭窗体时,将comm1控件关闭。
end;
procedure senddata;
var
i:integer;
commflg:boolean;
begin
viewstring:='';
commflg:=true;
for i:=1 to 6 do
begin
if not form1.comm1.writecommdata(@sbuf[i],1) then
begin
commflg:=false;
break;
end;
sleep(2);
viewstring:=viewstring+ inttohex(sbuf[i],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;
end.