温馨提示×

C#串口通讯收发数据怎么实现

c#
小亿
90
2024-02-29 14:55:15
栏目: 编程语言

在C#中实现串口通信收发数据,可以使用System.IO.Ports命名空间下的SerialPort类。以下是一个简单的示例代码:

using System;
using System.IO.Ports;

class Program
{
    static SerialPort _serialPort;
    
    static void Main()
    {
        _serialPort = new SerialPort("COM1", 9600); // 设置串口号和波特率
        _serialPort.Open(); // 打开串口
        
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); // 设置数据接收事件处理函数
        
        string message = "Hello, World!";
        _serialPort.WriteLine(message); // 发送数据
        
        Console.ReadLine(); // 等待用户输入
    }
    
    static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string data = sp.ReadLine(); // 读取接收到的数据
        Console.WriteLine("Received data: " + data);
    }
}

以上代码中,首先创建一个SerialPort对象,并指定串口号和波特率。然后打开串口,并设置数据接收事件处理函数。在Main函数中,发送数据使用WriteLine方法,接收数据则在DataReceivedHandler函数中通过ReadLine方法读取数据。最后通过Console.WriteLine打印接收到的数据。

需要注意的是,在使用完SerialPort对象后,需要及时关闭串口,可以在程序结束时调用_serialPort.Close()来关闭串口连接。

0