学堂 学堂 学堂公众号手机端

在C#中进行串口通信,通常可以使用System.IO.Ports命名空间中的SerialPort类

lewis 1年前 (2024-03-22) 阅读数 7 #技术

在C#中进行串口通信,通常可以使用System.IO.Ports命名空间中的SerialPort类。以下是一个简单的示例代码,演示如何在C#中打开串口、发送数据和接收数据:

usingSystem; usingSystem.IO.Ports; classSerialCommunication { staticvoidMain() { //创建一个新的SerialPort对象 SerialPortserialPort=newSerialPort("COM1",9600); //打开串口 serialPort.Open(); //发送数据 serialPort.WriteLine("Hello,World!"); //接收数据 stringreceivedData=serialPort.ReadLine(); Console.WriteLine("ReceivedData:"+receivedData); //关闭串口 serialPort.Close(); } }

在上面的示例中,我们首先实例化一个SerialPort对象,然后使用Open()方法打开串口,使用WriteLine()方法发送数据,使用ReadLine()方法接收数据,最后使用Close()方法关闭串口。在实际应用中,可能还需要处理异常、设置串口参数等操作。


版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门