I'm afraid that my outcome was rather boring but I hate it when the solution to a problem is not published.
I tried af0815's solution and it is incorporated here. Sadly I still could not connect to both serial outputs. I'm using a Waveshare USB to RS485 dongle for the MFCs and it may be part of the problem.
I tried slowing down the baudrate to the Arduino Mega but that did not solve the problem.
The following code connects to both serial connections every time:
{ TForm1 }
TForm1 = class(TForm)
LazSerial1: TLazSerial;
LazSerial2: TLazSerial;
Memo1: TMemo;
Timer1: TTimer;
Timer2: TTimer;
procedure FormCreate(Sender: TObject);
procedure LazSerial1RxData(Sender: TObject);
procedure LazSerial2RxData(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure Timer2Timer(Sender: TObject);
private
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{ TForm1 }
var
inputFrom1,
inputFrom2 : string ;
procedure TForm1.FormCreate(Sender: TObject);
var
workStr : string ;
begin
try
LazSerial1.Active:= true ;
LazSerial1.Open;
Application.ProcessMessages;
workStr := '' ;
if LazSerial1.Active then
begin
// fConnect.Show ;
repeat
LazSerial1.WriteData('@E121!');
sleep (1000) ;
if LazSerial1.DataAvailable then workStr := LazSerial1.ReadData ;
until workStr = '' ; //Was <>
end;
// fConnect.Close
except
showMessage ( 'Cannot open the Arduino serial port' ) ;
application.Terminate;
end; //try except
lazSerial2.Open;
lazSerial2.Active:= true ;
end;
procedure TForm1.LazSerial1RxData(Sender: TObject);
begin
while lazSerial1.DataAvailable do
inputFrom1 := inputFrom1 + lazSerial1.ReadData ;
end;
procedure TForm1.LazSerial2RxData(Sender: TObject);
begin
while lazSerial2.DataAvailable do
inputFrom2 := inputFrom2 + lazSerial2.ReadData ;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
lazSerial1.WriteData('@E121!');
lazSerial2.WriteData('A' + #13 );
end;
procedure TForm1.Timer2Timer(Sender: TObject);
begin
if inputFrom1 <> '' then
begin
memo1.Lines.Add(inputFrom1);
inputFrom1 := '' ;
end;
if inputFrom2 <> '' then
begin
memo1.Lines.Add(inputFrom2);
inputFrom2 := '' ;
end;
end;
end.
fConnect is simply a form that tells the user that the system is connecting.
I honestly don't know why this works. It's code that I wrote ages ago to connect and I made the mistake of trying to create an improved wheel. Perhaps it is the sleep command that is essential? That would perhaps tie with the fact that the previous version of the code would sometimes work if I debugged into it line by line.
The output is attached. The laser is responding to @E121! through the Mega (data from @ to !) and the Alicat MFC A is responding directly (twice) in the line starting A and ending N2.
Hil