Mega Code Archive

 
Categories / Delphi / VCL
 

A component for the serial device (TRS232)

Title: A component for the serial device (TRS232) Question: A component that provides functions to read and write synchron from the RS232 via strings Answer: Attached with this article is a full component that handles communication with the RS232. I want to point out only one interesting aspect. Every communication with the rs232 is asyncron. You never know exactly when bits are arriving... The ReadString method from TRS232 is like serializing the communication. You can call ReadString and pass the amount of characters that you would like to receive. The function only returns when enough characters did arrive or is running into a timeout. For some cases this is useful ! (During the loop it's doing a Application.ProcessMessages so that events from the main program can be executed !) Here is the ReadString method out of many other function from the component TRS323: function TRS232.ReadString(VAR aResStr: string; aCount: word ): boolean; var nRead: dword; Buffer: string; Actual, Before: TDateTime; TimeOutMin, TimeOutSec, lCount: word; begin Result := false; if not Connected then if not Connect then raise Exception.CreateHelp ('RS232.ReadString:'+ ' Connect not possible !', 101); aResStr := ''; TimeOutMin:=TimeOut div 60; TimeOutSec:=TimeOut mod 60; if (not Connected) or (aCount nRead := 0; lCount := 0; Before := Time; while lCount begin Application.ProcessMessages; SetLength(Buffer,1); if ReadFile( FComPortHandle, PChar(Buffer)^, 1, nRead, nil ) then begin if nRead 0 then begin aResStr := aResStr + Buffer; inc(lCount); end; Actual := Time; if Actual-BeforeEncodeTime(0, TimeOutMin, TimeOutSec, 0) then raise Exception.CreateHelp('RS232.ReadString: TimeOut !', 103); end else begin raise Exception.CreateHelp('RS232.ReadString: Read not possible !', 104); end; end; // while Result:=true; end;