Reputation: 3288
I have device which is connect to PC via USB Serial communication. I am performing following steps
So I think I have some way to close communication port forcefully.
Upvotes: 6
Views: 12763
Reputation: 198
I know the question is some years old, but I had the same problem few days ago. What me helped was discarding the in and out buffers before close().
this.serialPort.DiscardInBuffer();
this.serialPort.DiscardOutBuffer();
this.serialPort.Close();
Upvotes: 0
Reputation: 3288
I have found solution though it can not be called standard solution but though i don't have any problem with that solution because it solves my problem the solution is as per belove step
FIRST STEP:-
class clsRS232 : IDisposable
{
private SerialPort myPort;
public clsRS232()
{
myPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
}
public void OpenPort()
{
myPort.Open();
}
public void SendFunc(string str)
{
myPort.Write(str);
}
public string ReadFunc()
{
return myPort.ReadExisting();
}
public void Dispose()
{
myPort.Dispose();
}
}
SECOND STEP:-
using (clsRS232 mySerialPort = new clsRS232())
{
lock (mySerialPort)
{
mySerialPort.OpenPort();
mySerialPort.SendFunc(commandArg);//here "commandArg" is command or data you want to send to serial port
this.serialPortObj_DataReceived(mySerialPort.ReadFunc()); //here "serialPortObj_DataReceived()" is a user define method where received data will be passed
}
}
Upvotes: 2
Reputation: 1176
If you are communicationg with your hardware over a serial port and using a SerialEventListener, then I think a Serial.DATA_BREAK(Dont remember the exact name) event occurs. You could catch this in the SerialEvent method and close the connection from your program to your port. Hope this helps you to forcibly close your connection at the time of disconnection of the hardware.
Upvotes: 2
Reputation: 24937
Have you run .Close() on the comport when you are done on it?
You ideally need to Close() before you power off or disconnect the device.
Also, are you using SerialPort.GetPortNames()? If you are using USB comports and pull them out (or power them off) and then re-insert them again, they get a new name given to them by Windows.
Then you must re-enumerate them with SerialPort.GetPortNames(), to check what the new COM-name is.
I.e., your device may be called COM3 on first power on, on second power on it might be called COM4 and so on. After a number of cycles, it might be called COM3 again.
That's why you need to call GetPortNames, to find out if a "new" device appeared. (It's not really a new device, it is your device which powered back on.)
Upvotes: 1