在C#中,可以通過以下步驟設置DataReceived事件的回調函數:
SerialPort serialPort = new SerialPort("COM1");
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
在DataReceivedHandler方法中,首先將sender轉換為SerialPort對象,然后使用ReadExisting方法讀取收到的數據,并將數據打印到控制臺。
serialPort.Open();
通過以上步驟,可以設置DataReceived事件的回調函數,并在串口接收到數據時執行相應的處理操作。