Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Serial Port Auto closes

Tags:

c#

serial-port

Im trying to read data from a COM serial port, but the port is auto closing randomly, i dont know what to do, nowhere in my code i call the close method. i tried setup events on dispose, setup try catch and debug all catchs, but no luck.

Tried to create an infinity thread that when SerialPort.isOpen return false the thread reopen the serial port, it work but the thread eats the cpu at 100%..

Dont know what else to do...

The code that opens the serial

_serialPort.DataReceived += new SerialDataReceivedEventHandler(RecebendoDados);
_serialPort.Disposed += new EventHandler(PortaFechou);
_serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(PortaErro);
_serialPort.PinChanged += new SerialPinChangedEventHandler(PinMudou);                
_serialPort.Open();
PortIsOpen = _serialPort.IsOpen;
like image 553
Eduardo Estevão Avatar asked Dec 19 '25 12:12

Eduardo Estevão


1 Answers

Why do you keep the COM port opened? Just open it when you write then close it!
Use this:

    if (!serialPort1.IsOpen)
        serialPort1.Open();
    if (serialPort1.IsOpen)
    {
        serialPort1.WriteLine(inst.ToString());
        serialPort1.Close();
    }
like image 192
Bassem Akl Avatar answered Dec 21 '25 00:12

Bassem Akl