COM port is denied

c#, serial-port

Solution

If you are using an FTDI USB/Serial adapter, you can retrieve the state directly from the managed wrapper (FTDI Managed Driver Wrapper) and reinitialize your serial port based on the connected state.

Forgive my lack of experiance with FTDI devices, but this should reset your R-232 adapter:

FTD2XX_NET.FTDI device = new FTD2XX_NET.FTDI();
string port;
device.GetCOMPort(out port);

if (!string.IsNullOrEmpty(port) && (port.Equals(target)) && device.IsOpen)
{
    device.CyclePort();
    device.ResetDevice();
    device.ResetPort();
}

By my understanding `device.CyclePort()` will close any active connection (calls `FT_CLOSE`), unmounts the usb device, and reenumerates the device from the usb bus. This should be exactly the same as if you physically removed, and reinserted the adapter.

Also, according to the documentation for the Perl wrapper for the FTDI device library:

As with other bus controls, there is a wait period of 5-8 seconds after a CyclePort where any API call that requires direct connection to the device, like GetSerialByIndex() etc, will fail with FT_INVALID_HANDLE until it has completely stabilized. The application should account for this wait period, or setup a polling loop to detect the change in return status.

Problem

Hi I am trying to use COM port to read some registers using modbus protocol, everything works fine until I rebote modbus slave device, then I have error that com is denied, what I can do is or rebot computer or plug out and back in 'usb to com converter'. Seems that this device doesn't handle with com port properly. ``` using (port = new SerialPort(comPort)) { ushort[] registers = null; try { port.BaudRate = boudRate; port.DataBits = 8; port.Parity = Parity.None; port.StopBits = StopBits.One; port.Open(); // modbus reading registers port.Close(); return registers; } catch (Exception e) { Logs.AddToLog(e.Message); return registers; } } ```

Original source