I am using an arduino leonardo to control stepper motors from Visual Studio C++ software on a Win10 laptop. The laptop is connected to the arduino via serial (19200 baud).
At times, the software sends up to 20 commands per second to the arduino (there is at least 50ms between 2 commands, and the arduino processes a command in ~10ms).
During this "high frequency" phase, after several seconds of high responsiveness to commands, the arduino suddenly lags some 3 or 4 seconds behind, misses commands, etc.\
.
Experiment 1:
1- Run the software, waiting for the lag to appear
2- Send a command from the laptop
3- Immediately unplug the serial cable
Seconds after the cable was disconnected the arduino executes the command.
So I thought the problem was with the arduino taking time to process and not the laptop's software. Serial input processing is done in loop() with the following code :
void loop() {
if (Serial.available())
{
// tried with and without delay :
delay(10);
// Tried the 2 following methods of reading :
// METHOD 1
//char cmdBuffer[15];
//int lenCmd = Serial.readBytesUntil('.', cmdBuffer, 15);
//foo(cmdBuffer, lenCmd);
// METHOD 2
String stringRead = Serial.readString();
foobar(stringRead);
// Serial.Flush has changed and does not flush anymore
// But without flushing or with Serial.begin(19200); to reset the buffer
// the lag still appears.
}
}
// setup for completeness:
void setup() {
Serial.begin(19200);
Serial.setTimeout(x); // tried x = 5, 50, 500
}
I also tried Serial.setTimeout(x) in setup(), with x = 5, 50, 500.
Again, everything works as intended for some time and then instantly breaks.
.
Experiment 2:
1- Run the software, waiting for the bug to appear
2- Unplug-replug the serial cable (not reconnecting the software to the port nor shutting down the arduino)
3- Open the serial monitor of the arduino IDE
4- Communicating with the arduino works perfectly, there is no lag with the commands !
I guess something has gone wrong with what the software sends... Could the arduino slow down commands processing because a kind of spam protection was enabled ? And only on commands sent by the software ??
Pls help, I'm out of ideas