串口SerialPort

9

title: 串口SerialPort
description:
published: true
date: 2024-11-08T12:45:15.827Z
tags:
editor: markdown

dateCreated: 2024-11-08T12:45:11.051Z

SerialPort 类提供了许多方法和属性,用于配置、打开、关闭和管理串口通信。以下是常用的 SerialPort 方法和属性的详细介绍以及用法示例。

属性

  1. PortName: 获取或设置端口名称(例如 “COM1”)。

    serialPort.PortName = "COM1";
    
  2. BaudRate: 获取或设置波特率(例如 9600)。

    serialPort.BaudRate = 9600;
    
  3. Parity: 获取或设置奇偶校验位(例如 Parity.None)。

    serialPort.Parity = Parity.None;
    
  4. DataBits: 获取或设置数据位(例如 8)。

    serialPort.DataBits = 8;
    
  5. StopBits: 获取或设置停止位(例如 StopBits.One)。

    serialPort.StopBits = StopBits.One;
    
  6. Handshake: 获取或设置握手协议(例如 Handshake.None)。

    serialPort.Handshake = Handshake.None;
    
  7. ReadTimeout: 获取或设置读取操作的超时时间(以毫秒为单位)。

    serialPort.ReadTimeout = 500; // 500毫秒
    
  8. WriteTimeout: 获取或设置写入操作的超时时间(以毫秒为单位)。

    serialPort.WriteTimeout = 500; // 500毫秒
    
  9. IsOpen: 获取一个值,该值指示串口是否打开。

    bool isOpen = serialPort.IsOpen;
    
  10. DtrEnable: 获取或设置一个值,该值指示是否启用 Data Terminal Ready (DTR) 信号。

    serialPort.DtrEnable = true;
    
  11. RtsEnable: 获取或设置一个值,该值指示是否启用 Request to Send (RTS) 信号。

    serialPort.RtsEnable = true;
    

方法

  1. Open(): 打开串口连接。

    serialPort.Open();
    
  2. Close(): 关闭串口连接。

    serialPort.Close();
    
  3. Read(byte[] buffer, int offset, int count): 从串口读取数据到缓冲区。

    byte[] buffer = new byte[1024];
    int bytesRead = serialPort.Read(buffer, 0, buffer.Length);
    
  4. ReadLine(): 从串口读取一行数据。

    string line = serialPort.ReadLine();
    
  5. ReadExisting(): 读取串口缓冲区中的所有可用数据。

    string data = serialPort.ReadExisting();
    
  6. Write(byte[] buffer, int offset, int count): 将数据写入串口。

    byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes("Hello, Serial Port!");
    serialPort.Write(dataToSend, 0, dataToSend.Length);
    
  7. Write(string text): 将字符串写入串口。

    serialPort.Write("Hello, Serial Port!");
    
  8. WriteLine(string text): 将字符串写入串口并添加行结束符。

    serialPort.WriteLine("Hello, Serial Port!");
    
  9. DiscardInBuffer(): 清除接收缓冲区的数据。

    serialPort.DiscardInBuffer();
    
  10. DiscardOutBuffer(): 清除发送缓冲区的数据。

    serialPort.DiscardOutBuffer();
    

事件

  1. 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);
    }
    
  2. PinChanged: 当串口引脚状态变化时触发。

    serialPort.PinChanged += new SerialPinChangedEventHandler(PinChangedHandler);
    
    private static void PinChangedHandler(object sender, SerialPinChangedEventArgs e)
    {
       SerialPinChange change = e.EventType;
       Console.WriteLine("Pin Changed: " + change.ToString());
    }
    
  3. 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