c# serial port listener [closed]

做~自己de王妃 提交于 2019-12-23 04:47:44

问题


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.


回答1:


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.

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)
    {
        //....
    }
}


来源:https://stackoverflow.com/questions/29018001/c-sharp-serial-port-listener

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!