给你一个例子单元
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
SPComm, ComCtrls, StdCtrls,IniFiles,Registry;
type
TFrmMain = class(TForm)
Comm1: TComm;
Button1: TButton;
MemoMSG: TMemo;
Button2: TButton;
Button3: TButton;
Edit1: TEdit;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
procedure Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);
procedure SendData;
procedure Control(ykcode:byte);
procedure InitComm;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button1Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
ReceiveBuffer:array [0..64] of byte;
SendBuffer:array [0..64] of byte;
SendBufferLength:integer;
end;
var
FrmMain: TFrmMain;
implementation
{$R *.DFM}
procedure TFrmMain.InitComm ;
begin
comm1.StopComm;
Comm1.startcomm;
end;
procedure TFrmMain.Control(ykcode:byte);
begin
SendBuffer[0]:=$aa; SendBuffer[1]:=$07;
SendBuffer[2]:=strtoint(edit1.text)-1;
SendBuffer[3]:=strtoint(edit1.text)-1;
SendBuffer[4]:=ykcode;
SendBuffer[5]:=not(SendBuffer[0]+SendBuffer[1]+
SendBuffer[2]+SendBuffer[3]+
SendBuffer[3]);
SendBufferLength:=6;
SendData;
end;
procedure TFrmMain.SendData;
var
viewstring:string;
i:integer;
begin
comm1.WritecommData(pchar(@SendBuffer),SendBufferLength);
for i:=0 to SendBufferLength-1 do
viewstring:=viewstring+inttohex(SendBuffer,2)+' ';
viewstring:='发送:'+viewstring;
MemoMSG.Lines.Add(viewstring);
MemoMSG.Lines.Add(' ');
end;
procedure TFrmMain.Comm1ReceiveData(Sender: TObject; Buffer: Pointer;
BufferLength: Word);
var
viewstring:string;
i:integer;
begin
Move(Buffer^,pchar(@ReceiveBuffer)^, bufferlength);
for i:=0 to bufferlength-1 do
begin
viewstring:=viewstring+inttohex(ReceiveBuffer,2)+' ';
end;
viewstring:='接收:'+viewstring;
MemoMSG.Lines.Add(viewstring);
MemoMSG.Lines.Add('');
if memoMSG.Lines.Count >500 then
memoMSG.Clear ;
viewstring:='';
MemoMSG.Invalidate;
End;
procedure TFrmMain.FormCreate(Sender: TObject);
begin
InitComm ;
end;
procedure TFrmMain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
comm1.StopComm;//关闭窗体时,将comm1控件关闭。
end;
procedure TFrmMain.Button1Click(Sender: TObject);
begin
control($ff);
end;
procedure TFrmMain.Button3Click(Sender: TObject);
begin
control($00);
end;
procedure TFrmMain.Button2Click(Sender: TObject);
begin
control($ab);
end;
end.