I have C # code that communicates with three different COM ports. COM ports are actually three serial ports for USB converters.
Each time you turn off 'on' and 'on', the codes with which it exchanges switch each time, and then initializes three COM ports, tries to send and read data, and then closes the COM port. This continues to continue for a predetermined number of cycles. My problem is that after about 8 or 9 iterations, the COM port connection stops working. Sometimes it throws an error saying that the port is closed, sometimes it does not throw any exceptions, but in fact it does not read or write anything from the COM port. For a while he only wrote, but did not read the data.
What could be the reason and any tips for debugging this problem?
EDIT:
The port closes or stops abruptly even in the middle of the program, as shown below:
SerialPort.Write("ss");
SerialPort.Read("ss");
Some part of the code I'm using
public string Read(string readCommand)
{
string str = "";
_port.WriteLine("\r");
_port.WriteLine(readCommand + "\r");
Thread.Sleep(0x3e8);
str = _port.ReadExisting();
return str;
}
public void Write(string command)
{
_port.WriteLine(command + "\r");
Thread.Sleep(100);
if (_port.ReadExisting() == string.Empty)
{
throw new IOException("Error writing to COM");
}
}
public void Initialize()
{
if (_port == null)
{
_port = new SerialPort(this.PortName.ToString(), this.BaudRate, this.Parity, this.DataBits, this.StopBits);
_port.Handshake = this.Handshake;
}
try
{
if (!_port.IsOpen)
{
_port.Open();
if (Read("") == string.Empty)
{
throw new IOException("Device not connected or powered on");
}
}
}
catch (Exception)
{
this.Close();
}
}
Thank...
Manoj source
share