Difference between revisions of "Serial unit"

From Lazarus wiki
Jump to navigationJump to search
Line 1: Line 1:
 +
__TOC__
 +
 
Unit '''Serial''' in FPC supports work with serial port. It provides many Ser* functions.
 
Unit '''Serial''' in FPC supports work with serial port. It provides many Ser* functions.
  

Revision as of 15:59, 19 September 2022

Unit Serial in FPC supports work with serial port. It provides many Ser* functions.

Example of usage

Program TestSerialPortCom;
{
  Usage:
  TestSerialPortCom
    Uses default port COM1.
  TestSerialPortCom 8 'Hello'
    Uses COM8 and outputs 'Hello' before waiting for an answer.
  
  The program will open a serial port and output 'Hello', after that the code will wait until
  a CR (#13) is received, or a key is pressed.
}
uses
  serial, crt;

var
  serialhandle : LongInt;
  ComPortName  : String;
  s,tmpstr,txt : String;
  ComIn        : String;
  ComPortNr    : integer;
  writecount   : integer;
  status       : LongInt;
  Flags        : TSerialFlags; { TSerialFlags = set of (RtsCtsFlowControl); }
  ErrorCode    : Integer;

begin
  ComPortNr:= 1;
  tmpstr:= '';
  txt:= '';

  writeln('Parameters: ', ParamCount);
  if (ParamCount>0) then
  begin
    tmpstr:= ParamStr(1);
    val(tmpstr, ComPortNr, ErrorCode);

    if (ParamCount>1) then
      txt:= ParamStr(2);
  end;

  str(ComPortNr,tmpstr);
 
  ComPortName:= 'COM'+tmpstr+':';
  writeln('Using: '+ComPortname);

  serialhandle := SerOpen(ComPortName);
  Flags:= []; // None
  SerSetParams(serialhandle, 9600, 8, NoneParity, 1, Flags); 
  
  s:= txt; // use the input text
  writeln('Output: '+s);
  s:= s+#13+#10; // CR + LF
  writecount:= length(s);

  status:= SerWrite(serialhandle, s[1], writecount);

  // For debugging only
  writeln('Status: ', status, ', WriteCount: ', writecount);

  if status > 0 then
  begin
    writeln('Waiting for answer');
    s:= '';
    ComIn:= '';
    while (Length(ComIn)<10) and (status>=0) and not KeyPressed do 
    begin
      status:= SerRead(serialhandle, s[1], 10);
      if (s[1]=#13) then 
        status:= -1; // CR => end serial read

      if (status>0) then
      begin 
        ComIn:= ComIn+s[1];
        writeln('Status: ', status, ', Len: ', length(ComIn), ', ASCII: ', ord(s[1]), ', Input: ', ComIn);
      end;  
    end;
  end
  else
    writeln('Error: unable to send');

  SerSync(serialhandle); // flush out any remaining before closure

  SerFlushOutput(serialhandle); // discard any remaining output

  SerClose(serialhandle);
end.

When timeout starts

Q: I'm trying to figure out when the timeout timer in SerRead/SerReadTimeout starts.

A (by FPC developer Christo Crause): FPC uses the OS provided functionality to interact with the serial port. On Windows the timeout seems to start when the read request is made - Link. On POSIX (at least Linux) it depends on the specific set of flags specified , scroll down to the discussion on canonical/noncanonical mode for the details - Link.