C# hangs on closing connection with Arduino

114 Views Asked by At

I'm writing a C# program that sends some simple commands to Arduino. via USB serial virtual port.

Sometimes happen that the program hangs, even if the code is protected by a try/catch block.

When I saw the problem the problem seem to be in closing the port.

The function is very simple:

void Send() {
  try {  
    Debug.WriteLine("SR1 "+rel+" "+status);
    _serialArduino.Open();
    Debug.WriteLine("SR2");
    _serialArduino.WriteLine(string.Format("switch {0} {1}\n", rel, Convert.ToSByte(status)));
    Debug.WriteLine("SR3 '"+_serialArduino.ReadLine()+"'");
    _serialArduino.Close();
    Debug.WriteLine("SR4");
    Thread.Sleep(400);
  } catch (Exception e) {
    LogManager.Write(string.Format("ERR SwitchRel({0}, {1}) - {2}", rel, status, e.Message));
  }
}

I read about a problem during the Close function but in this case no DataReceived event handler is defined (==null).

Any idea?

* Edited to add some details *

After days of debugging and log analysis I discovered the following:

  • I'm working on a device running Win7Embedded Standard
  • The application is written in C#
  • after some time (or maybe caused from something unknown, so far) the port connecting Arduino disappeared from the list of the enumerated ports
  • the program initially reports on my log 'Device disconnected' and then 'Port COM9 does not exist' messages
  • The device manager reports COM9 on the 'Ports' tree (!!)
  • If I shut the program and re-run it, it reports 'COM9 does not exist' and if I list the ports the COM9 does not appear

My guess is that the usbser driver is in a mess.
The only solution, so far, is reset the board.
Is there a way to reset the driver without reboot and check if it returns in a known state? Or maybe is the DotNet Framework that does not detect the port ?

0

There are 0 best solutions below