另帖出我在delphi中的代码:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, OleCtrls, MSCommLib_TLB;
type
TForm1 = class(TForm)
Button1: TButton;
MSComm1: TMSComm;
Button2: TButton;
procedure Button1Click(Sender: TObject);
function ParityCheck(command:string):Integer;
procedure InitialCom;
procedure MSComm1Comm(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.ParityCheck(command:string):Integer;
var
i:integer;
begin
Result:=0;
for i:=1 to length(Command) do
Result:=Result+Ord(Command);
Result:=(128+Result mod 128);
end;
procedure TForm1.InitialCom;
begin
if mscomm1.PortOpen then
mscomm1.PortOpen:=False;
mscomm1.CommPort:=1;
mscomm1.OutBufferCount:= 0
// 清除传输缓冲区
mscomm1.InBufferCount := 0
//清空接收缓冲区
mscomm1.InputLen := 0
//每次从接收缓冲区读取的字符数。0 :读取缓存区的全部内容 返回值:INTEGER X型变量
mscomm1.RThreshold := 1
//接收数据时产生Oncomm 事件的字符数 1:收到每一个字符都会产生ONCOMM 事件
mscomm1.InputMode := 1
mscomm1.Settings := '2400,N,8,1';
mscomm1.RThreshold:=1;
mscomm1.PortOpen := True;
mscomm1.DTREnable := False
mscomm1.RTSEnable := False;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
SParity:String;
IParity:array[1 .. 1] of byte;
i:Integer;
ParityBit:String;
begin
SParity:='22401000'+'D';
IParity[1]:=ParityCheck(SParity);
ParityBit:=chr(IParity[1]);
InitialCom;
MSComm1.InBufferCount:= 0;
For i:=0 to 2 do
begin
sleep(50);
mscomm1.Output:='#'+'22401000D';
mscomm1.Output:=ParityBit;
mscomm1.Output:='!';
end
end;
procedure TForm1.MSComm1Comm(Sender: TObject);
var
iReceived:array[0..8096] of integer;
revCount:Integer;
recbin:OleVariant;
recint:Variant;
i:Integer;
BInput:byte;
begin
if Mscomm1.CommEvent=2 then
begin
revCount:=mscomm1.InBufferCount
// 返回接收缓冲区内等待读取的字节数,可通过设置该属性为0来清空接收缓冲区
recbin:=Mscomm1.Input;
recint:=VarArrayCreate([0,2048], varByte);
recint:=recbin;
For i:=0 to revCount-1 do
begin
bInput:=recint;
iReceived:=Integer(bInput);
end;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
application.Terminate;
end;
end.