串口控制(100分)

  • 主题发起人 主题发起人 seaant
  • 开始时间 开始时间
S

seaant

Unregistered / Unconfirmed
GUEST, unregistred user!
在调用api进行串口编程时如何使用writefile和readfile进行读写,需要哪些先期处理。
p.s.:求助delphi串口编程资料。
 
先给你一段例子,供参考:
write方法
procedure WriteToComm( BufferToWrite: TCommBuffer; NumberToWrite: DWORD );
var
dwNumberOfWritten, dwLastError: DWORD;

begin
lpOverlapped^.Offset := 0;
dwNumberOfWritten := 0;
repeat
if not WriteFile( hCommFile, BufferToWrite,
NumberToWrite, dwNumberOfWritten,
lpOverlapped ) then
begin
dwLastError := GetLastError;
if dwLastError <> ERROR_IO_PENDING then
begin
Raise ECommError.Create( 'Error write serial port' );
Exit;
end;

if not GetOverlappedResult( hCommFile, lpOverlapped^,
dwNumberOfWritten, True ) then
begin
Raise ECommError.Create( 'Error write serial port' );
Exit;
end;
end;

Inc( lpOverlapped^.Offset, dwNumberOfWritten );
Dec( NumberToWrite, dwNumberOfWritten );
until (NumberToWrite <= 0);
end;

read方法
procedure ReadFromComm( var BufferToRead: TCommBuffer;
var NumberOfRead: DWORD );
var
dwLastError, dwEvtMask: DWORD;
CommStat: TComStat;
bolOverlappedResult: Boolean;

begin
lpOverlapped^.Offset := 0;
dwEvtMask := 0;

if not ClearCommError( hCommFile, dwLastError, @CommStat ) then
begin
Raise ECommError.Create( 'Error read serial port' );
Exit;
end;

if not WaitCommEvent( hCommFile, dwEvtMask, lpOverlapped ) then
begin
dwLastError := GetLastError;
if dwLastError = ERROR_IO_PENDING then
begin
bolOverlappedResult := GetOverlappedResult( hCommFile,
lpOverlapped^, NumberOfRead, False );
if not bolOverlappedResult then
begin
Exit;
end;
end
else
begin
Exit;
end;
end;

if not ReadFile( hCommFile, BufferToRead,
CommStat.cbInQue, NumberOfRead,
lpOverlapped ) then
begin
Raise ECommError.Create( 'Error read serial port' );
Exit;
end;

if not GetOverlappedResult( hCommFile, lpOverlapped^,
NumberOfRead, True ) then
begin
Raise ECommError.Create( 'Error read serial port' );
Exit;
end;
end;
如果要资料可以给我来信。
 
spcomm的源代码和串口资料
 
我在PlayICQ上上传了一个源码。希望能合乎你的要求,北京红十字血液中心……,你搜索一下吧。
 
去下载SPCOMM那个控键很好用的并且支持多线程的.
 
lp414,你现在对串口编程应该很熟悉了吧。
 
后退
顶部