.NET SerialPort DataReceived event not firing

前端 未结 9 670
忘掉有多难
忘掉有多难 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:25

    I am using the Virtual Serial Port Driver. This problem takes me the whole day. And finally fix by creating a pair of port. One port send message and another one receive message instead of using the same port to send and receive message. I guess that is how Null Modem Emulator works.

    Dim mySerialPort As SerialPort = New SerialPort("COM1")
    Dim mySerialPort2 As SerialPort = New SerialPort("COM2")
    
    Sub Main()
        SerialPortCommunicate()
    End Sub
    
    Public Sub SerialPortCommunicate()
        mySerialPort.BaudRate = 9600
        mySerialPort.Parity = Parity.None
        mySerialPort.StopBits = StopBits.One
        mySerialPort.DataBits = 8
        mySerialPort.Handshake = Handshake.None
        mySerialPort.DtrEnable = True
        mySerialPort.RtsEnable = True
    
        mySerialPort2.BaudRate = 9600
        mySerialPort2.Parity = Parity.None
        mySerialPort2.StopBits = StopBits.One
        mySerialPort2.DataBits = 8
        mySerialPort2.Handshake = Handshake.None
        mySerialPort2.DtrEnable = True
        mySerialPort2.RtsEnable = True
    
        AddHandler mySerialPort2.DataReceived, AddressOf DataReceivedHandler
    
        mySerialPort.Open()
        mySerialPort2.Open()
    
        mySerialPort.Write("Hello World")
    
        Console.WriteLine("Press any key to continue...")
        Console.WriteLine()
        Console.ReadKey()
        mySerialPort.Close()
        mySerialPort2.Close()
    End Sub
    
    Private Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
        Dim sp As SerialPort = CType(sender, SerialPort)
        Dim indata As String = sp.ReadExisting()
        Console.WriteLine("Data Received:")
        Console.Write(indata)
    End Sub
    

    Result: Data Received: Hello World Press any key to continue...

    0 讨论(0)
  • 2020-12-09 23:30

    I ran into a similarly odd problem recently, but only on some machines. As Dave Swersky noted, this may have been a threading issue, especially if you were running under .NET 4.0 or later.

    In .NET 4.0 the event handler is triggered on a ThreadPool thread, and under certain circumstances there may be a substantial delay before that occurs. (In my code, which had been working perfectly under .NET 2.0, problems were observed as soon as we upgraded to .NET 4.5. The event handler would often be triggered much later than would be expected, and sometimes it would not get triggered at all!)

    Calling ThreadPool.SetMinThreads(...) with a bigger value for the completion threads made the issue disappear as quickly as it had arrived. In the context of our application ThreadPool.SetMinThreads(2, 4) was sufficient. On the machines where the problem was observed, the default values (as obtained by calling ThreadPool.SetMinThreads) were both 2.

    0 讨论(0)
  • 2020-12-09 23:35

    Two days ago I had the same problem and it was a big headache because I needed to deliver the app today. So.. after too much googleashion I supposed that the issue was another thing and not my code.

    My solution was uninstall McAfee antivirus and all things related with this. When I saw the logs of McAfee it had records about stop threads and I assumed that the SerialDataReceivedEventHandler() run in a thread.

    I hope this solution works for you. Regards.

    0 讨论(0)
  • 2020-12-09 23:36

    I have had similar issue when running such a driver from a Form, as well, though no VSPE just a plain SP. Believe this was a STA-model issue as moving to including it in a console app fixed enough.

    0 讨论(0)
  • 2020-12-09 23:45
    port.DtrEnable = true;
    

    This solved it for me, the DataTransmitReady flag was not enabled, so no data was received.

    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题