C# Windows Forms SerialPort 串口通信使用方法

SerialPort 是一个 .NET Framework 中的类,用于在 Windows Forms 应用程序中与串口进行通信。它提供了许多方法和属性,可以轻松地配置和控制串口通信。下面是 SerialPort1 的常用用法详解:

1.导入命名空间:using System.IO.Ports;

2.实例化 SerialPort1 对象:

public partial class MainForm : Form

{

private SerialPort serialPort1; public MainForm()

{

InitializeComponent(); // 实例化 SerialPort1 对象

serialPort1 = new SerialPort();

}

}

3.配置串口参数:

serialPort1.PortName = "COM1"; // 串口号

serialPort1.BaudRate = 9600; // 波特率

serialPort1.DataBits = 8; // 数据位

serialPort1.Parity = Parity.None; // 校验位

serialPort1.StopBits = StopBits.One;// 停止位

4.打开和关闭串口:

 // 打开串口 serialPort1.Open();

// 关闭串口 serialPort1.Close();

5.数据发送和接收

// 发送数据
serialPort1.Write("Hello, SerialPort!");

// 接收数据
private void SerialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    //string receivedData = serialPort1.ReadExisting();
    // 处理接收到的数据

byte[] buffer = new byte[serialPort1.BytesToRead];

serialPort1.Read(buffer, 0, buffer.Length);

string receivedData = Encoding.ASCII.GetString(buffer);

// 在 UI 线程上更新文本框

Invoke(new Action(() => { textBox1.AppendText(receivedData); }));
}
6.错误处理

// 注册 ErrorReceived 事件处理程序
serialPort1.ErrorReceived += SerialPort1_ErrorReceived;

// ErrorReceived 事件处理程序
private void SerialPort1_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
    // 处理错误
}
 

猜你喜欢

转载自blog.csdn.net/qq_33790894/article/details/131721105