delphi中使用mscomm控件2008-01-28 14:11Mscomm是微軟一個(gè)強(qiáng)大的串口通訊的控件,其強(qiáng)大,簡單的特點(diǎn)今我們不舍,在delphi中我們也可以使用它。下面這些代碼是針對發(fā)送和接收為16進(jìn)制處理的。
var
senddata:array[1..10] of char;
reData:array of Variant;
sendstr:string;
restr:string;
i:longint;
begin
mscomm1.CommPort := 1; //指定端口
mscomm1.Settings := ‘9600,N,8,1‘; //其它參數(shù)
mscomm1.InBufferSize := 1024; //接收緩沖區(qū)
mscomm1.OutBufferSize := 1024; //發(fā)送緩沖區(qū)
mscomm1.InputMode := comInputModeBinary; //接收模式
mscomm1.InputLen := 0; //一次讀取所有數(shù)據(jù)
mscomm1.SThreshold := 0; //一次發(fā)送所有數(shù)據(jù)
mscomm1.InBufferCount := 0; //清空讀取緩沖區(qū)
mscomm1.OutBufferCount := 0; //清空發(fā)送緩沖區(qū)
mscomm1.PortOpen:=true; //打開端口
MSComm1.RThreshold := 16; //設(shè)置接收多少字節(jié)開產(chǎn)生oncomm事件
senddata[1]:=chr($06); //要發(fā)送的數(shù)據(jù)
senddata[2]:=chr($03);
senddata[3]:=chr($00);
senddata[4]:=chr($03);
senddata[5]:=chr($10);
sendstr:=‘‘;
for i:=1 to 5 do
sendstr:=sendstr + senddata[i];
mscomm1.output:=sendstr; //發(fā)送數(shù)據(jù)
i:=0;
bzw:=false;
repeat
sleep(10);
Application.ProcessMessages;
i := i + 1;
If i > 30000 Then
begin
showmessage(‘發(fā)送超時(shí)!‘);
break;
end;
Until bzw = true;
redata:=mscomm1.Input; 接收數(shù)據(jù)
restr:=‘‘;
for i:=0 to vararrayhighbound(redata,1) do
restr:=restr + inttohex(redata[i],2)+‘ ‘;
mscomm1.PortOpen:=false;
flatmemo1.Text:=restr;
end;
//oncomm事件
procedure TForm1.MSComm1Comm(Sender: TObject);
begin
case mscomm1.CommEvent of
comEvReceive: bzw := true;
end;
end;
最后,記事發(fā)布軟件時(shí)要帶上Mscomm32.ocx文件。




