简介
C# 中的
SerialPort
类提供了对串行端口(如 COM 端口)进行通信的功能。通过SerialPort
类,你可以打开、关闭端口,读取和写入数据以及设置通信参数等。下面是对SerialPort
类的一些详细解释:
创建 SerialPort 对象
SerialPort serialPort = new SerialPort("COM1", 9600);
创建了一个名为
serialPort
的串口对象,并指定了端口名称"COM1"
和波特率9600
。
设置串口参数
serialPort.BaudRate = 9600; serialPort.Parity = Parity.None; serialPort.DataBits = 8; serialPort.StopBits = StopBits.One;
除了在构造函数中设置外,你还可以通过上述属性来设置串口的波特率、奇偶校验位、数据位和停止位等参数。
打开和关闭串口
serialPort.Open(); // 在完成通信后记得关闭串口 serialPort.Close();
使用
Open
方法打开串口,使用Close
方法关闭串口。
读取数据、写入数据
byte[] buffer= new byte[1024] int bytesRead = serialPort.Read(buffer, 0, buffer.Length);
使用
Read
方法从串口读取数据到指定的缓冲区中。byte[] data = { 0x01, 0x02, 0x03 }; serialPort.Write(data, 0, data.Length);
使用
Write
方法将数据写入串口发送出去。using System; using System.IO.Ports; class SerialCommunication { static void Main() { // 创建串口对象,并指定串口号和波特率 SerialPort serialPort = new SerialPort("COM1", 9600); try { // 打开串口 serialPort.Open(); // 设置要发送的数据 byte iWay = 0x01; // 数据1 byte tempLight = 100; // 数据2 byte tempEnd = ((byte)(0x24 ^ iWay ^ tempLight)); // 计算校验位 byte[] sendtemp = new byte[] { 0x24, iWay, tempLight, tempEnd }; // 组装要发送的数据 // 向串口写入数据 serialPort.Write(sendtemp, 0, sendtemp.Length); Console.WriteLine("数据发送成功!"); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } catch (IOException e) { Console.WriteLine(e.Message); } finally { // 关闭串口 serialPort.Close(); } } }
事件处理
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); }
你可以注册
DataReceived
事件来处理从串口接收到的数据。using System; using System.IO.Ports; class SerialCommunication { static void Main() { // 创建串口对象,并指定串口号和波特率 SerialPort serialPort = new SerialPort("COM1", 9600); try { // 打开串口 serialPort.Open(); // 设置数据接收事件处理程序 serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); Console.WriteLine("开始接收数据,按任意键退出..."); Console.ReadKey(); } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); } catch (IOException e) { Console.WriteLine(e.Message); } finally { // 关闭串口 serialPort.Close(); } } private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("接收到的数据: " + indata); } }
在接收数据的示例中,我们通过
DataReceived
事件来异步接收数据,并在DataReceivedHandler
事件处理程序中处理接收到的数据。