C# read only Serial port when data comes

一曲冷凌霜 提交于 2019-11-27 19:55:13

You will have to add an eventHandler to the DataReceived event.

Below is an example from msdn.microsoft.com, with some edits: see comments!:

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();
    Debug.Print("Data Received:");
    Debug.Print(indata);
}

Everytime data comes in, the DataReceivedHandler will trigger and prints your data to the console. I think you should be able to do this in your code.

you need to subscribe to the DataReceived event before opening the port, then listen to that event when triggered.

    private void OpenSerialPort()
    {
        try
        {
            m_serialPort.DataReceived += SerialPortDataReceived;
            m_serialPort.Open();
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(ex.Message + ex.StackTrace);
        }
    } 

    private void SerialPortDataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        var serialPort = (SerialPort)sender;
        var data = serialPort.ReadExisting();
        ProcessData(data);
    }

Serial, when there is data in the buffer, the data received event is triggered, this doesn't mean that you got all your data at once. You may have to wait for number of times to get all of your data; this is where you need to process the received data separate, perhaps keep them on cache somewhere, before you do the final processing.

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