在C#中,使用System.IO.Ports.SerialPort
类可以实现串口通信。以下是一个简单的示例,展示了如何使用SerialPort
类进行串口通信:
System.IO.Ports
命名空间。using System.IO.Ports;
SerialPort
对象,并配置串口参数。例如,要使用COM1端口,波特率为9600,数据位为8,停止位为1,无奇偶校验:SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.Open();
SerialPort
对象添加事件处理程序,以便在接收到数据时执行相应操作。这里我们使用DataReceived
事件:serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
serialPort_DataReceived
方法,处理接收到的数据:private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
string receivedData = System.Text.Encoding.ASCII.GetString(buffer);
Console.WriteLine("接收到的数据: " + receivedData);
}
serialPort.Close();
将以上代码整合到一个完整的示例中:
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class Program
{
static void Main(string[] args)
{
SerialPort serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
serialPort.Open();
serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
Console.WriteLine("按任意键关闭串口...");
Console.ReadKey();
serialPort.Close();
}
private static void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[serialPort.BytesToRead];
serialPort.Read(buffer, 0, buffer.Length);
string receivedData = System.Text.Encoding.ASCII.GetString(buffer);
Console.WriteLine("接收到的数据: " + receivedData);
}
}
}
运行此示例,程序将打开COM1端口,并在接收到数据时在控制台输出接收到的数据。按任意键关闭串口。