我做过好多串口设备的通讯,都是这么做的,没问题啊,空间我没用过,不知道怎么样。Function OpenCommPort(const CommStr:array of char): integer; var sDcb:TDCB; cComBuf:array[0..10]of char; begin lstrcpy(cCombuf,CommStr); gComID := CreateFile(cCombuf, GENERIC_READ or GENERIC_WRITE, 0, // comm devices must be opened w/exclusive-access nil, // no security attrs OPEN_EXISTING, // comm devices must use OPEN_EXISTING 0, // not overlapped I/O 0); // hTemplate must be NULL for comm devices if gComID < 0 then begin Result := ERROR_ICURS232OPEN; exit; end; SetupComm(gComID,1024,1024); GetCommState(gComID,sDcb); sDcb.BaudRate := CBR_9600; sDcb.ByteSize := 7; sDcb.parity := EVENPARITY; sDcb.stopbits := ONESTOPBIT; SetCommState(gComID,sDcb); SetRWTimeOut(COMM_CHARTO, COMM_MUTITO, COMM_CONSTTO_DEFAULT); Result := gComID;end;procedure CloseCommPort; begin CloseHandle(gComId); end;Function Send232Data(const SendStr:array of char;const SendLen:integer):integer; var iSendNums: Cardinal; begin PurgeComm(gComID, PURGE_TXCLEAR or PURGE_RXCLEAR); if not WriteFile(gComId,SendStr,SendLen,iSendNums,nil) then begin Result := ERROR_ICURS232WRITE; exit; end; if (int(iSendNums) <> SendLen) then begin Result := ERROR_ICURS232WRITEBADDATA; exit; end; Result := iSendNums; end;
var
sDcb:TDCB;
cComBuf:array[0..10]of char;
begin
lstrcpy(cCombuf,CommStr);
gComID := CreateFile(cCombuf,
GENERIC_READ or GENERIC_WRITE,
0, // comm devices must be opened w/exclusive-access
nil, // no security attrs
OPEN_EXISTING, // comm devices must use OPEN_EXISTING
0, // not overlapped I/O
0); // hTemplate must be NULL for comm devices if gComID < 0 then begin
Result := ERROR_ICURS232OPEN;
exit;
end; SetupComm(gComID,1024,1024); GetCommState(gComID,sDcb); sDcb.BaudRate := CBR_9600;
sDcb.ByteSize := 7;
sDcb.parity := EVENPARITY;
sDcb.stopbits := ONESTOPBIT;
SetCommState(gComID,sDcb); SetRWTimeOut(COMM_CHARTO, COMM_MUTITO, COMM_CONSTTO_DEFAULT);
Result := gComID;end;procedure CloseCommPort;
begin
CloseHandle(gComId);
end;Function Send232Data(const SendStr:array of char;const SendLen:integer):integer;
var
iSendNums: Cardinal;
begin PurgeComm(gComID, PURGE_TXCLEAR or PURGE_RXCLEAR); if not WriteFile(gComId,SendStr,SendLen,iSendNums,nil) then begin
Result := ERROR_ICURS232WRITE;
exit;
end;
if (int(iSendNums) <> SendLen) then begin
Result := ERROR_ICURS232WRITEBADDATA;
exit;
end;
Result := iSendNums;
end;