delphitcomport

Delphi 7 TComPort OnRxChar not fire


I'm using TComPort I use the OnRxChar event to control when byte are arrived.

I receive 3 bytes word for each command i send, but sometimes, OnRxChar receive only 2 bytes the remaining byte is not received, even if sent correctly 3 byte at time.

I think the remaining bytes is still in some buffers, but OnRxChar not fire for the last byte, why?

What am I doing wrong?

EDIT 1

Piece of code

procedure BraccioRobot.ComPort3RxChar(Sender: TObject; Count: Integer);
var
  i:integer;
  BB : integer;
  Dist:double;
  Buff:array [0..10] of byte;
begin
FMsg:='Byte in:'+IntToStr(Count);
Synchronize(Log);
ComPort3.Read(Buff, Count);

for i:=0 to Count-1 do begin
  Rxbuff[CountRx+i]:=Buff[i];
end;
CountRx:=CountRx+Count;

if CountRx<3 then begin
  exit;
end;


// --------------------------
// 80 lines of code where I process the received data 

EDIT 2 if after having received only 2 bytes, I send other 3 bytes, OnRxChar fire and i recive 4 bytes this time, the last of first word and the entire second word

like this: A1 A2 | A3 B1 B2 B3

EDIT 3

procedure BraccioRobot.Log;
begin
  Memo1.Lines.Add(FMsg);
end;

I removed the call to Synchronize and now the event is called. I need something to make the log when I do the tests. How do?


Solution

  • To the best of my knowledge, TComPort.OnRxChar event is executed in the main thread. You are calling Synchronize(Log) in this event handler. This is bad. See TThread.Synchronize where this is stated:

    Warning: Do not call Synchronize from within the main thread. This can cause an infinite loop.

    And this can also explain why you are missing an event call. The TComPort.OnRxChar event is already called with a Synchronize() statement, and adding another Synchronize(Log) call can cause messages from the system to get lost.

    Just call Log without the Synchronize and it will work.