串口SerialPort
title: 串口SerialPort
description:
published: true
date: 2024-11-08T12:45:15.827Z
tags:
editor: markdown
dateCreated: 2024-11-08T12:45:11.051Z
SerialPort
类提供了许多方法和属性,用于配置、打开、关闭和管理串口通信。以下是常用的 SerialPort
方法和属性的详细介绍以及用法示例。
属性
PortName: 获取或设置端口名称(例如 “COM1”)。
serialPort.PortName = "COM1";
BaudRate: 获取或设置波特率(例如 9600)。
serialPort.BaudRate = 9600;
Parity: 获取或设置奇偶校验位(例如 Parity.None)。
serialPort.Parity = Parity.None;
DataBits: 获取或设置数据位(例如 8)。
serialPort.DataBits = 8;
StopBits: 获取或设置停止位(例如 StopBits.One)。
serialPort.StopBits = StopBits.One;
Handshake: 获取或设置握手协议(例如 Handshake.None)。
serialPort.Handshake = Handshake.None;
ReadTimeout: 获取或设置读取操作的超时时间(以毫秒为单位)。
serialPort.ReadTimeout = 500; // 500毫秒
WriteTimeout: 获取或设置写入操作的超时时间(以毫秒为单位)。
serialPort.WriteTimeout = 500; // 500毫秒
IsOpen: 获取一个值,该值指示串口是否打开。
bool isOpen = serialPort.IsOpen;
DtrEnable: 获取或设置一个值,该值指示是否启用 Data Terminal Ready (DTR) 信号。
serialPort.DtrEnable = true;
RtsEnable: 获取或设置一个值,该值指示是否启用 Request to Send (RTS) 信号。
serialPort.RtsEnable = true;
方法
Open(): 打开串口连接。
serialPort.Open();
Close(): 关闭串口连接。
serialPort.Close();
Read(byte[] buffer, int offset, int count): 从串口读取数据到缓冲区。
byte[] buffer = new byte[1024]; int bytesRead = serialPort.Read(buffer, 0, buffer.Length);
ReadLine(): 从串口读取一行数据。
string line = serialPort.ReadLine();
ReadExisting(): 读取串口缓冲区中的所有可用数据。
string data = serialPort.ReadExisting();
Write(byte[] buffer, int offset, int count): 将数据写入串口。
byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes("Hello, Serial Port!"); serialPort.Write(dataToSend, 0, dataToSend.Length);
Write(string text): 将字符串写入串口。
serialPort.Write("Hello, Serial Port!");
WriteLine(string text): 将字符串写入串口并添加行结束符。
serialPort.WriteLine("Hello, Serial Port!");
DiscardInBuffer(): 清除接收缓冲区的数据。
serialPort.DiscardInBuffer();
DiscardOutBuffer(): 清除发送缓冲区的数据。
serialPort.DiscardOutBuffer();
事件
DataReceived: 当接收到数据时触发。
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.WriteLine(indata); }
PinChanged: 当串口引脚状态变化时触发。
serialPort.PinChanged += new SerialPinChangedEventHandler(PinChangedHandler); private static void PinChangedHandler(object sender, SerialPinChangedEventArgs e) { SerialPinChange change = e.EventType; Console.WriteLine("Pin Changed: " + change.ToString()); }
ErrorReceived: 当串口错误发生时触发。
serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceivedHandler); private static void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e) { SerialError error = e.EventType; Console.WriteLine("Error Received: " + error.ToString()); }
完整示例
下面是一个完整的示例,展示了如何使用上述属性、方法和事件进行串口通信:
using System;
using System.IO.Ports;
using System.Threading;
class SerialPortExample
{
static SerialPort serialPort;
static void Main(string[] args)
{
serialPort = new SerialPort()
{
PortName = "COM1",
BaudRate = 9600,
Parity = Parity.None,
DataBits = 8,
StopBits = StopBits.One,
Handshake = Handshake.None,
ReadTimeout = 500,
WriteTimeout = 500
};
serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
serialPort.PinChanged += new SerialPinChangedEventHandler(PinChangedHandler);
serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceivedHandler);
try
{
serialPort.Open();
Console.WriteLine("Serial port opened.");
// 写入数据
serialPort.WriteLine("Hello, Serial Port!");
// 主程序循环
while (true)
{
// 模拟一些串口通信操作
// ...
Thread.Sleep(1000); // 假装在做一些工作
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received: " + indata);
}
private static void PinChangedHandler(object sender, SerialPinChangedEventArgs e)
{
SerialPinChange change = e.EventType;
Console.WriteLine("Pin Changed: " + change.ToString());
}
private static void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e)
{
SerialError error = e.EventType;
Console.WriteLine("Error Received: " + error.ToString());
}
}
这个示例展示了如何配置和使用 SerialPort
类进行串口通信,同时处理各种事件以监控数据接收、引脚状态变化和错误。通过调整示例中的参数和逻辑,可以适应不同的应用需求。
You use the GetPortNames method to retrieve the valid ports for the current computer.
If a SerialPort object becomes blocked during a read operation, do not abort the thread. Instead, either close the base stream or dispose of the SerialPort object.
| | |
| ———————————————————————————————————————————————————————– | ——————————————————- |
| DiscardInBuffer() | Discards data from the serial driver's receive buffer. |
| DiscardOutBuffer() | Discards data from the serial driver's transmit buffer. |
https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=net-8.0