How to implement data transmission and reception in C# serial communication

In C#, you can use the SerialPort class under the System.IO.Ports namespace to implement serial communication for sending and receiving data. Below is a simple example code:

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);
    }
}

Firstly, a SerialPort object is created in the above code with the specified port number and baud rate. The port is then opened, and a data receive event handling function is set. In the Main function, data is sent using the WriteLine method, and data is received by reading data using the ReadLine method in the DataReceivedHandler function. Finally, the received data is printed using Console.WriteLine.

It is important to note that after using the SerialPort object, you should promptly close the serial port. You can close the port connection by calling _serialPort.Close() when the program ends.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds