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

   2024-11-02 7340
核心提示:在C#中实现串口通信收发数据,可以使用System.IO.Ports命名空间下的SerialPort类。以下是一个简单的示例代码:using System;usin

在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()来关闭串口连接。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号