怎么用serialport接收数据
时间: 2023-07-24 10:28:42 浏览: 68
SerialPort类中提供了多种方法用于接收串行端口数据。以下是一个基本的示例,演示了如何使用SerialPort类接收数据:
```csharp
using System;
using System.IO.Ports;
public class SerialPortExample
{
public static void Main(string[] args)
{
// 创建SerialPort对象
SerialPort serialPort = new SerialPort("COM1", 9600);
try
{
// 设置接收数据的事件处理程序
serialPort.DataReceived += SerialPort_DataReceived;
// 打开串行端口
serialPort.Open();
Console.WriteLine("Listening for data...");
// 等待用户按下回车键退出程序
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
finally
{
// 关闭串行端口
serialPort.Close();
}
}
private static void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// 获取SerialPort对象
SerialPort serialPort = (SerialPort)sender;
// 读取接收到的数据
string data = serialPort.ReadExisting();
Console.WriteLine("Data received: " + data);
}
}
```
在上述示例中,我们创建了一个SerialPort对象并指定了串行端口名称和波特率。然后,我们设置了DataReceived事件的处理程序SerialPort_DataReceived。当串行端口接收到数据时,该事件将被触发并调用该处理程序。
在SerialPort_DataReceived处理程序中,我们首先将sender对象转换为SerialPort类型,然后使用ReadExisting方法读取接收到的数据。最后,我们在控制台上打印出接收到的数据。
请注意,此示例仅用于演示目的,并且可能需要根据具体的应用程序和硬件配置进行调整。另外,如果需要连续接收数据,可以考虑使用Read方法替代ReadExisting方法。