I'm writing two applications, which are supposed to communicate to each other. One is written in C++ for Arduino (Teensy, more specifically), second is a desktop app written in C#.
Usually the communication works correctly. However, sometimes I have trouble receiving information from Teensy. In those situations the log says:
00:00:00.00 | Serial port service | Trying to open port COM4...
00:00:00.00 | Serial port service | Closing port COM4...
00:00:00.00 | Serial port service | Opening port COM4...
00:00:00.00 | Serial port service | Opened port COM4...
00:00:00.00 | Serial port service | Bytes to read: 0
The code behind this log looks like following (serialPort is a System.IO.Ports.SerialPort):
public void OpenPort(string port)
{
logService.AddLog(SerialPortLogSource, $"Trying to open port {port}...");
ClosePort();
serialPort.PortName = port;
try
{
logService.AddLog(SerialPortLogSource, $"Opening port {port}...");
serialPort.Open();
if (serialPort.IsOpen)
logService.AddLog(SerialPortLogSource, $"Opened port {port}...");
else
logService.AddLog(SerialPortLogSource, $"Open call exited, but port is not opened");
opened = true;
this.port = port;
configurationService.Configuration.LastUsedPort = port;
configurationService.Save();
logService.AddLog(SerialPortLogSource, $"Bytes to read: {serialPort.BytesToRead}");
DataReceived?.Invoke(this, EventArgs.Empty);
}
catch
{
logService.AddLog(SerialPortLogSource, $"Failed to open port {port}...");
opened = false;
this.port = null;
}
}
When I afterwards initiate communication from the device, I get nothing. However, what's interesting, if I only open the serial port monitor in Arduino IDE, I receive some information, which I was supposed to get in my application and moreover from this point on, communication with my application starts working. This is a scenario, which is reproducible every single time.
The whole project is available on GitLab, more specifically, this is MacroKeyboard.Satellite.
What may cause such weird behavior? What may happen in Arduino IDE's serial port monitor, what unclogs the serial port?