c#串口监听器 [英] c# serial port listener

查看:75
本文介绍了c#串口监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中是否有任何串口侦听器,如果串口上有任何数据,它会调用我的函数吗?我唯一的想法是使用无限循环,如下所示:

Is in C# any serial port listener, that will call my function if there will be any data on serial port? My only idea is to use infinite loop, something like this:

while true
    if someDataOnSerialPort
        callmyfunction(serialPortData)

?如果有任何数据,任何会调用我的函数的处理程序?谢谢.

? Any handler that will call my function if there will be any data? Thanks.

推荐答案

是的,有使用 DataReceived 事件通知新数据并从该事件处理程序内部而不是内部调用您的函数无限循环.

Yes there is use the DataReceived event to be notified that new data and call your function from inside that event handler instead of inside a infinite loop.

这是 MSDN 中的示例,稍作修改以使用您的函数名称

Here is the example from the MSDN modified slightly to use your function names

using System;
using System.IO.Ports;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM1");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        //Console.WriteLine("Data Received:");
        //Console.Write(indata);

        callmyfunction(indata);
    }

    private static void callmyfunction(string data)
    {
        //....
    }
}

这篇关于c#串口监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆