C语言
主页 > 软件编程 > C语言 >

C#串行通信serialPort的使用

2024-03-31 | 佚名 | 点击:

System.IO.Ports.SerialPort 类是C#中用于串行通信的类。它提供了一组属性和方法,用于配置串行端口、读取和写入数据,以及处理串行通信中的事件。

初始化SerialPort对象

首先,你需要创建一个SerialPort对象,并设置其端口名称(PortName)、波特率(BaudRate)等属性。

1

2

3

4

5

6

7

8

9

using System.IO.Ports; 

   

SerialPort serialPort = new SerialPort(); 

serialPort.PortName = "COM1"; // 串行端口名称 

serialPort.BaudRate = 9600; // 波特率 

serialPort.DataBits = 8; // 数据位 

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

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

serialPort.Handshake = Handshake.None; // 控制协议

打开和关闭串行端口

在配置好SerialPort对象后,你需要打开串行端口以开始通信。

1

2

3

serialPort.Open(); 

// ... 执行串行通信操作 ... 

serialPort.Close(); // 完成后关闭串行端口

读取和写入数据

使用SerialPort对象的ReadLine、ReadExisting、ReadByte等方法读取数据,使用WriteLine、Write等方法写入数据。

1

2

3

4

5

6

7

// 写入数据 

serialPort.WriteLine("Hello, serial port!"); 

   

// 读取数据 

string data = serialPort.ReadLine(); // 读取一行数据,直到遇到换行符 

// 或者 

string existingData = serialPort.ReadExisting(); // 读取所有可用数据

事件处理

SerialPort类提供了几个事件,允许你在特定情况下执行代码,例如当接收到数据时。

1

2

3

4

5

6

7

8

9

serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); 

   

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) 

    SerialPort sp = (SerialPort)sender; 

    string indata = sp.ReadExisting(); 

    Console.WriteLine("Data Received:"); 

    Console.Write(indata); 

}

在这个例子中,当接收到数据时,DataReceivedHandler方法会被调用,并读取并打印接收到的数据。

注意事项

确保你有正确的串行端口名称,以及正确的配置参数(波特率、数据位、校验位、停止位等)。
在多线程环境中,处理串行端口事件时要小心线程安全问题。
不要忘记在完成串行通信后关闭串行端口。
异常处理
在使用SerialPort时,应该准备好处理可能发生的异常,例如当尝试打开不存在的端口或发生I/O错误时。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

try 

    serialPort.Open(); 

    // ... 串行通信操作 ... 

catch (Exception ex) 

    Console.WriteLine("Error: " + ex.Message); 

finally 

    if (serialPort.IsOpen) 

    { 

        serialPort.Close(); 

    } 

}

这个try-catch-finally块确保了即使发生异常,串行端口也会被正确关闭。

原文链接:
相关文章
最新更新