There is no serial port control available in Delphi, so you first need to add the ActiveX control MSCOMM to the component palette. This is a very good control. It can not only operate the serial port, but also control the Modem. The following is a specific example to illustrate how to use the MSCOMM control to develop a serial communication program.
Create a Communication.dPR project, change the form's Name property to CommForm, change the title to The Communication Test, and select File/Save As to store the new form as CommFrm.pas.
The corresponding code is as follows:
Variable description
var
CommForm: TCommForm;
ss :string;
savef,readf:file of char;
i,j :longint;
initialization
procedure TCommForm.FormCreate(Sender: TObject);
begin
mscomm.commport:=1;
mscomm.settings:='9600,n,8,1';
mscomm.inputlen:=1;
mscomm.inbuffercount:=0;
mscomm.portopen:=true;
ss:='';
i:=0;
j:=0;
assignfile(savef,'save1');
rewrite(savef);
assignfile(readf,'read1');
reset(readf);
end;
Setting OK
procedure TCommForm.btnConfirmClick(Sender: TObject);
begin
if mscomm.portopen then
mscomm.portopen:=false;
mscomm.commport:=strtoint(edtCommport.text);
mscomm.settings:=edtCommsetting.Text;
end;
transfer event
procedure TCommForm.MSCommComm(Sender: TObject);
var
filenrc:char;
buffer :variant;
s1: string;
c:char;
begin
case mscomm.commEvent of
comEvSend:
begin
while not(eof(readf)) do
begin
read(readf,filenrc);
mscomm.output:=filenrc;
j:=j+1;
lblDisplay.caption:=inttostr(j);
if mscomm.outbuffercount>=2 then
break;
end;
end;
comEvReceive:
begin
buffer:=mscomm.Input;
s1:=buffer;
c:=s1[1];
ss:=ss+c;
i:=i+1;
lblDisplay.caption:=c+inttostr(i);
write(savef,c);
if (c=chr(10))or(c=chr(13)) then
begin
lblDisplay.caption:='cr'+inttostr(i);
memDisplay.lines.add(ss);
ss:='';
end;
end;
end;
end;