C# can't read serial port after few hours?

412 views Asked by At

i have a project which read serial port data from device, and My operating system is windows 10. i Have read this :

  1. C# Serial Port Check if Device is Connected

2. SerialPort.Close() freezes application if the USB COM Port in use has been removed

but my code may only work 6 hours if there is no input from device. The solution for now is close form after that open form again.

 SerialPort myPort = new SerialPort();
   private void Scanning_Load(object sender, EventArgs e)
    {
        myPort.BaudRate = 9600;
        myPort.PortName = "COM4";
        if (SerialPort.GetPortNames().ToList().Contains(comPortname))
        {
            if (!myPort.IsOpen)
            {
                myPort.Open();
            }
             myPort.DataReceived += getReceivedata;
        }
     }
    private  void getReceivedata(object sender,
                             SerialDataReceivedEventArgs e)
    {
        SerialPort spL = (SerialPort)sender;
        string data_rx = spL.ReadLine();
        this.Invoke((MethodInvoker)delegate
        {
         Console.Write(data_rx);
        });
    }
1

There are 1 answers

4
user246821 On

This may be a result of power management (or power options) settings. You didn't state which OS you're using, or if your device is attached via USB.

Win 10:

  • In search box next to Start icon, type: device manager
  • Right-click your desired device
  • Select "Properties"
  • If "Allow the computer to turn off this device to save power" option exits, uncheck it. Click OK.

Other settings that you may need to review are "Power Options" which can be found in the Control Panel or in search box next to Start icon, type: power options (then click "Additonal power settings"). Since you stated that it works for 6 hours. You might check which settings are set at 6 hours (360 minutes).