C# Serial Communication Guide
In C#, serial communication can be done using the SerialPort class in the System.IO.Ports namespace. Below is a simple example code demonstrating how to open a serial port, send data, and receive data in C#.
using System;
using System.IO.Ports;
class SerialCommunication
{
static void Main()
{
// 创建一个新的SerialPort对象
SerialPort serialPort = new SerialPort("COM1", 9600);
// 打开串口
serialPort.Open();
// 发送数据
serialPort.WriteLine("Hello, World!");
// 接收数据
string receivedData = serialPort.ReadLine();
Console.WriteLine("Received Data: " + receivedData);
// 关闭串口
serialPort.Close();
}
}
In the above example, we first create a SerialPort object, then open the serial port using the Open() method, send data using the WriteLine() method, receive data using the ReadLine() method, and finally close the serial port using the Close() method. In actual applications, additional operations such as handling exceptions and setting serial port parameters may also be required.