简体   繁体   中英

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

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);
        });
    }

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM