.NET SerialPort DataReceived event not firing

前端 未结 9 674
忘掉有多难
忘掉有多难 2020-12-09 22:52

I have a WPF test app for evaluating event-based serial port communication (vs. polling the serial port). The problem is that the DataReceived event doesn\'t seem to be fir

9条回答
  •  时光取名叫无心
    2020-12-09 23:46

    I use the exact same setup, it works perfectly now but had to solve many many problems to get there.

    Here is why my initial declaration looks like:

    comControl = new SerialPort();
    
    //This is important - determine your min nb of bytes at which you will fire your event, mine is 9
    comControl.ReceivedBytesThreshold = 9; 
    
    //register the event handlers
    comControl.DataReceived += new SerialDataReceivedEventHandler(OnReceive);
    comControl.PinChanged += new SerialPinChangedEventHandler(OnPinChanged);
    

    I seperated the open port and close port methods since i often check if the com port has been closed.

    public bool OpenPort()
    {
        try
        {
            //must keep it open to maintain connection (CTS)
            if (!comControl.IsOpen)
            {
                 comControl.Open();
                 comControl.RtsEnable = true;
            }
        }
        catch (Exception e)
        {
            //error handling here
        }
    }
    

    Lastly, verify that your Virtual Com Port driver is installed properly and that you are using the right port, a plug and play for my adapter was not enough. If you want to create a sort of control that will allow you to pick the ports available at runtime, the following command will give you the available ports:

    System.IO.Ports.SerialPort.GetPortNames()
    

提交回复
热议问题