如何在 C# 中使用 SerialPort 端口对象的 dataReceived 事件?

How do I use dataReceived event of the SerialPort Port Object in C#?(如何在 C# 中使用 SerialPort 端口对象的 dataReceived 事件?)
本文介绍了如何在 C# 中使用 SerialPort 端口对象的 dataReceived 事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个小型应用程序来收集从连接到 COM10 的外部传感器接收到的数据.我已经成功创建了一个小型 C# 控制台对象和应用程序,它使用 for 循环在固定的时间段内打开端口并将数据流式传输到文件.

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 application that opens the port and streams data to a file for a fixed period of time using a for-loop.

我想将此应用程序转换为使用 dataReceived 事件进行流式传输.看完置顶5 个 SerialPort 提示,我似乎仍然无法让它工作,也不知道我错过了什么.我重写了控制台应用程序,以便所有代码都在 Main 中并粘贴在下面.有人可以帮我解释一下为什么即使我知道硬件正在向端口发送数据,事件处理程序 port_OnReceiveDatazz 也没有被调用?

I would like to convert this application to use the dataReceived event to stream instead. After reading the Top 5 SerialPort Tips, I still can't seem to get this to work and don't know what I am missing. I rewrote the console application so that all the code is in Main and is pasted below. Can someone please help enlighten me as to why the event handler port_OnReceiveDatazz is not being called even though I know that there is data being sent to the port by the hardware?

谢谢

感谢 @Gabe,@Jason Down 和 @abatishchev 提供所有建议.我很难过,似乎无法让事件处理程序工作.也许它与设备有关.我可以只在线程中读取端口并将数据直接流式传输到文件中.

Thanks to @Gabe, @Jason Down, and @abatishchev for all the suggestions. I am stumped and can't seem to get the event handler to work. Perhaps it has something to do with the device. I can live with just reading the port in a thread and streaming the data straight to file.

代码

namespace serialPortCollection
{   class Program
    {
        static void Main(string[] args)
        {
            
            const int bufSize = 2048;
            Byte[] buf = new Byte[bufSize]; //To store the received data.

            SerialPort sp = new SerialPort("COM10", 115200);
            sp.DataReceived += port_OnReceiveDatazz; // Add DataReceived Event Handler

            sp.Open();
            sp.WriteLine("$"); //Command to start Data Stream

            // Wait for data or user input to continue.
            Console.ReadLine();
           
            sp.WriteLine("!"); //Stop Data Stream Command
            sp.Close();
        }
        
       // My Event Handler Method
        private static void port_OnReceiveDatazz(object sender, 
                                   SerialDataReceivedEventArgs e)
        {
            SerialPort spL = (SerialPort) sender;
            const int bufSize = 12;
            Byte[] buf = new Byte[bufSize];
            Console.WriteLine("DATA RECEIVED!");
            Console.WriteLine(spL.Read(buf, 0, bufSize));
        }
    }
}

推荐答案

我认为你的问题是:**

sp.DataReceived += port_OnReceiveDatazz;

不应该是:

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

您可能还必须将握手设置为 RequestToSend(通过握手枚举).

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

更新:

发现一个建议说您应该先打开端口,然后分配事件处理程序.也许这是一个错误?

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

所以不要这样:

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

这样做:

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

让我知道这是怎么回事.

Let me know how that goes.

这篇关于如何在 C# 中使用 SerialPort 端口对象的 dataReceived 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)