Function OpenCOM(comid : integer) : integer; //打开串口
var
bSuccess:boolean;
begin
result := -1;
try
COMName := 'COM' + inttostr(comid + 1);
FileHandle:=CreateFile(Pchar(COMName),GENERIC_READ or GENERIC_WRITE,0,nil,
OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
if Filehandle=INVALID_HANDLE_VALUE then
begin
exit;
end;
dcb.DCBlength:=sizeof(DCB);
setupComm(Filehandle,1024,1024);
bSuccess:=GetCommState(FileHandle,dcb);
if not bSuccess then exit;
dcb.BaudRate:=9600; //波特率
dcb.ByteSize:=8; //数据位
dcb.Parity:=NOPARITY;
dcb.StopBits:=ONESTOPBIT;
bSuccess:=SetCommState(FileHandle,dcb);
zeromemory(@ToData,sizeof(ToData));
ToData.ReadIntervalTimeout:=10;
todata.ReadTotalTimeoutMultiplier:=1;
todata.ReadTotalTimeoutConstant:=1;
ToData.WriteTotalTimeoutConstant:=50;
ToData.WriteTotalTimeoutMultiplier:=2;
result := 0;
except
end;
end;
function CloseCOM : integer;
begin
Closehandle(FileHandle);
result := 0;
end;
function DataCheckOut(soudatastr : array of char;outstr : pchar) : integer;
var
tmpchar : array[0..256] of char;
rebyte : array[0..128] of byte;
tmpstr : String;
i : integer;
retstr : String;
tmpbyte : byte;
begin
retstr := '';
result := -1;
Bintohex(@soudatastr[0],@tmpchar[0],64);
tmpstr := string(strpas(@tmpchar[0]));
rebyte[0] := Hex2Dec(copy(tmpstr,1,2));
if rebyte[0] = $2 then
begin
rebyte[1] := Hex2Dec(copy(tmpstr,3,2));
if rebyte[1] <= 0 then exit;
delete(tmpstr,1,4);
tmpbyte := rebyte[1];
if rebyte[1] > 1 then
retstr := copy(tmpstr,3,rebyte[1]*2-2)
else
retstr := '';
for i := 1 to rebyte[1] do
begin
rebyte[1+i] := Hex2Dec(copy(tmpstr,1,2));
tmpbyte := tmpbyte + rebyte[1+i];
delete(tmpstr,1,2);
end;
rebyte[rebyte[1]+2] := Hex2Dec(copy(tmpstr,1,2));
rebyte[rebyte[1]+3] := Hex2Dec(copy(tmpstr,3,2));
if rebyte[rebyte[1]+2] <> tmpbyte then exit;
if rebyte[rebyte[1]+3] <> $3 then exit;
StrCopy(outstr,pchar(retstr));
result := rebyte[2];
end;
end;
function ReadDataFromCom(Inbuf : array of char;inlen : integer;outstr : pchar;outcount : integer) : integer; //
var
count:dword;
hevent:hwnd;
lap:OVERLAPPED;
stat:COMSTAT;
bsuccess:boolean;
i,k:integer;
tmpchar : array[0..128] of char;
returnval : integer;
begin
count := 0;
bsuccess:=WriteFile(filehandle,Inbuf,inlen,count,nil);
Application.ProcessMessages;
sleep(600);
if not bsuccess then
begin
result := -2;
exit;
end;
for k := 0 to 2 do
begin
i:=0;
bsuccess := ClearCommError(filehandle,count,@stat);
if not bsuccess then
begin
result := -3;
exit;
end;
while stat.cbInQue <= 4 do
begin
i:=i+1;
if i>50 then
exit;
ClearCommError(filehandle,count,@stat);
sleep(10);
end;
bsuccess:=ReadFile(FileHandle,tmpchar,stat.cbInQue,count,nil);
if not bsuccess then
begin
result := -4;
exit;
end;
returnval := DataCheckOut(tmpchar,outstr);
if returnval >= 0 then
begin
Result := returnval;
exit;
end else
result := -11;
end;
end;
上面的代码可能对你有帮助