How do I use dataReceived event of the SerialPort Port Object in C#?

后端 未结 7 1767
無奈伤痛
無奈伤痛 2020-11-28 07:26

I am attempting to create a small application to collect data received from an external sensor attached to COM10. I have successfully created a small C# console object and

7条回答
  •  天命终不由人
    2020-11-28 07:34

    I think your issue is the line:**

    sp.DataReceived += port_OnReceiveDatazz;

    Shouldn't it be:

    sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);

    **Nevermind, the syntax is fine (didn't realize the shortcut at the time I originally answered this question).

    I've also seen suggestions that you should turn the following options on for your serial port:

    sp.DtrEnable = true;    // Data-terminal-ready
    sp.RtsEnable = true;    // Request-to-send
    

    You may also have to set the handshake to RequestToSend (via the handshake enumeration).


    UPDATE:

    Found a suggestion that says you should open your port first, then assign the event handler. Maybe it's a bug?

    So instead of this:

    sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
    sp.Open();
    

    Do this:

    sp.Open();
    sp.DataReceived += new SerialDataReceivedEventHandler (port_OnReceiveDatazz);
    

    Let me know how that goes.

提交回复
热议问题