size : 2587
uploaded_on : Fri Oct 30 00:00:00 1998
modified_on : Wed Dec 8 14:03:24 1999
title : Serial port
org_filename : ComPort.Txt
author : J. Welter
authoremail : jwelter@sawtek.com
description : How do you send data to a serial port
keywords : Com port
tested : not tested yet
submitted_by : The CKB Crew
submitted_by_email : ckb@netalive.org
uploaded_by : nobody
modified_by : nobody
owner : nobody
lang : plain
file-type : text/plain
category : delphi-system32bit
__END_OF_HEADER__
> I need to send something (anything - it doesn't matter what) to the serial
> port (COM 2).
> Help tells that we can use standard CreateFile('COM2',...) function to
> communicate with port but I dont believe it - I tried and got nothing
You can make it work with a little more effort. Here are some more clues:
fUnit: DWORD; { Unit descriptor handle}
fUnitDescriptor: string; { Unit descriptor Pascal string }
fUnitDescriptor := 'COM2';
procedure TRs232.OpenPort(descriptor: PChar);
begin
fUnit := CreateFile(descriptor, GENERIC_READ or GENERIC_WRITE,
0,nil,OPEN_EXISTING,0,0);
end;
function TRs232.GetOpenPortError: BOOLEAN;
var
isOK: BOOLEAN;
Error: DWORD;
begin
isOK:=(fUnit <> INVALID_HANDLE_VALUE); //DWORD(-1)
if not isOK then
begin
Error := GetLastError;
{case fUnit of}
case Error of
IE_BADID: ShowMessage('"' + fUnitDescriptor + '" invalid or unsupported');
IE_BAUDRATE: ShowMessage('"' + fUnitDescriptor + '" baudrate unsupported');
IE_BYTESIZE: ShowMessage('Specified bytesize is invalid');
IE_DEFAULT: ShowMessage('Default parameters are in error');
IE_HARDWARE: ShowMessage('"' + fUnitDescriptor + '" not available');
IE_MEMORY: ShowMessage('"' + fUnitDescriptor + '" - unable to allocate queues');
IE_NOPEN: ShowMessage('"' + fUnitDescriptor + '" is not open');
IE_OPEN: ShowMessage('"' + fUnitDescriptor + '" is already open');
else
{ShowMessage('Note: "' + fUnitDescriptor + '" returned error ' +
IntToStr(Error)); }
end;
end;
Result:=isOK;
end;
function TRs232.Output(lpBuffer: PChar): BOOLEAN;
var
lpBytesSent,nBufferSize: LongWord;
begin
nBufferSize := StrLen(lpBuffer);
Result := WriteFile(fUnit, //handle to file to write to
lpBuffer, // pointer to data to write to file
nBufferSize, // number of bytes to write
lpBytesSent, // pointer to number of bytes written
nil); // pointer to structure needed for overlapped IO
end;
function TRs232.Enter(nBytesToRead: LongWord; lpString: PChar; var
lpBytesRead: LongWord): BOOLEAN;
begin
Result := ReadFile(fUnit,
lpString,
nBytesToRead,
lpBytesRead,
nil);
end;
destructor TRs232.Destroy;
begin
if not CloseHandle(fUnit) then
ShowMessage('Error closing port "' + fUnitDescriptor + '"');
inherited Destroy;
end;