在C#中实现串口通信收发数据,可以使用System.IO.Ports命名空间下的SerialPort类
在C#中实现串口通信收发数据,可以使用System.IO.Ports命名空间下的SerialPort类。以下是一个简单的示例代码:
usingSystem;
usingSystem.IO.Ports;
classProgram
{
staticSerialPort_serialPort;
staticvoidMain()
{
_serialPort=newSerialPort("COM1",9600);//设置串口号和波特率
_serialPort.Open();//打开串口
_serialPort.DataReceived+=newSerialDataReceivedEventHandler(DataReceivedHandler);//设置数据接收事件处理函数
stringmessage="Hello,World!";
_serialPort.WriteLine(message);//发送数据
Console.ReadLine();//等待用户输入
}
staticvoidDataReceivedHandler(objectsender,SerialDataReceivedEventArgse)
{
SerialPortsp=(SerialPort)sender;
stringdata=sp.ReadLine();//读取接收到的数据
Console.WriteLine("Receiveddata:"+data);
}
}
以上代码中,首先创建一个SerialPort对象,并指定串口号和波特率。然后打开串口,并设置数据接收事件处理函数。在Main函数中,发送数据使用WriteLine方法,接收数据则在DataReceivedHandler函数中通过ReadLine方法读取数据。最后通过Console.WriteLine打印接收到的数据。
需要注意的是,在使用完SerialPort对象后,需要及时关闭串口,可以在程序结束时调用_serialPort.Close()来关闭串口连接。
版权声明
本文仅代表作者观点,不代表博信信息网立场。