//---------------------------------------------------------------------
//这是我以前写的一个初始化串口函数,不知道对你有没有帮助
//---------------------------------------------------------------------
function TMainForm.InitCommPort(iPortNo:Integer):Boolean ;
var commName:String ;
lpdcb:TDCB;
rCommTimeouts:COMMTIMEOUTS;
begin
result:=false ;
CloseHandle(ahCom[iPortNo]);
try
commName:=format('Com%d',[iPortNo]) ;
ahCom[iPortNo]:=CreateFile(pAnsiChar(commName),generic_read or
generic_write,0,nil,open_existing,
file_attribute_normal,0);//´ò¿ª´®ÐпÚ
if ahCom[iPortNo]=invalid_handle_value then
begin
// ShowMessage('²»ÄÜ´ò¿ª'+String(sComName));
CloseHandle(ahCom[iPortNo]);
exit;
end;
bSuccessFlag:=SetupComm(ahCom[iPortNo],4096,4096); //ÉèÖÃCOMÊäÈ룬Êä³ö»º³åÇø
if not bSuccessFlag then
begin
// ShowMessage('²»ÄÜÉèÖÃ'+String(sComName));
CloseHandle(ahCom[iPortNo]);
exit;
end;
bSuccessFlag:=GetCommState(ahCom[iPortNo],lpdcb); //»ñÈ¡DCBµ±Ç°Ä¬ÈÏÉèÖÃ
if not bSuccessFlag then
begin
// ShowMessage('²»ÄÜ»ñµÃDCB²ÎÊý!');
CloseHandle(ahCom[iPortNo]);
exit;
end;
lpdcb.baudrate:=btl;
lpdcb.ByteSize:=zjs;
lpdcb.Parity:=NoParity;
lpdcb.StopBits:=OneStopBit;
bSuccessFlag:=SetCommState(ahCom[iPortNo],lpdcb); //ÓÃDCB²ÎÊýÌî³äDCB
if not bSuccessFlag then
begin
// ShowMessage('²»ÄÜÉèÖÃDCB!');
CloseHandle(ahCom[iPortNo]);
exit;
end;
PurgeComm(ahCom[iPortNo],PURGE_RXCLEAR or PURGE_RXABORT or PURGE_TXCLEAR or PURGE_TXABORT);//Çå¿Õ´®¿Ú»º³åÇøËùÓÐÊý¾Ý
ClearCommError(ahCom[iPortNo], lpError, lpStat);
with rCommTimeouts do
begin
ReadIntervalTimeout:=0;
ReadTotalTimeoutMultiplier:=0;
ReadTotalTimeoutConstant:=250; //¶Á³¬Ê±Îª0.25Ãë
WriteTotalTimeoutMultiplier:=0;
WriteTotalTimeoutConstant:=250; ////д³¬Ê±Îª0.25Ãë
end;
SetCommTimeouts(ahCom[iPortNo], rCommTimeouts);
abComInitFlag[iPortNo] := True;
Result:=true;
except
Application.MessageBox(PAnsiChar('³õʼ»¯´®¿ÚCOM' + intToStr(iPortNo) + 'ʧ°Ü!'),'Ìáʾ', MB_OK + MB_ICONWARNING);
end;
end ;