C#实现串口辅助类 实现串口读写

一个C#实现串口辅助类,带有读写与重连功能的示例代码: ``` using System; using System.IO.Ports; using System.Threading; public class SerialPortHelper { private SerialPort serialPort; private bool isConnected = false; private bool isReading = false; private Thread readThread; public SerialPortHelper(string portName, int baudRate) { serialPort = new SerialPort(portName, baudRate); serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(ErrorReceivedHandler); } public bool Connect() { if (!isConnected) { try { serialPort.Open(); isConnected = true; } catch { isConnected = false; } } return isConnected; } public bool Disconnect() { if (isConnected) { try { serialPort.Close(); isConnected = false; } catch { isConnected = true; } } return !isConnected; } public bool Write(byte[] buffer, int offset, int count) { if (isConnected) { try { serialPort.Write(buffer, offset, count); return true; } catch { return false; } } else { return false; } } public void StartReading() { if (!isReading) { readThread = new Thread(new ThreadStart(ReadData)); readThread.Start(); } } public void StopReading() { if (isReading) { isReading = false; readThread.Join(); } } private void ReadData() { isReading = true; while (isReading) { try { int bytesToRead = serialPort.BytesToRead; if (bytesToRead > 0) { byte[] buffer = new byte[bytesToRead]; serialPort.Read(buffer, 0, bytesToRead); if (DataReceived != null) { DataReceived(buffer); } } else { Thread.Sleep(10); } } catch { isReading = false; } } } private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { if (DataReceived != null) { int bytesToRead = serialPort.BytesToRead; byte[] buffer = new byte[bytesToRead]; serialPort.Read(buffer, 0, bytesToRead); DataReceived(buffer); } } private void ErrorReceivedHandler(object sender, SerialErrorReceivedEventArgs e) { if (isReading) { isReading = false; readThread.Join(); } if (ErrorReceived != null) { ErrorReceived(e.EventType); } } public delegate void DataReceivedDelegate(byte[] buffer); public event DataReceivedDelegate DataReceived; public delegate void ErrorReceivedDelegate(SerialError eventType); public event ErrorReceivedDelegate ErrorReceived; } ``` 使用示例: ``` SerialPortHelper serialPortHelper = new SerialPortHelper("COM1", 9600); serialPortHelper.Connect(); serialPortHelper.Write(new byte[] { 0x01, 0x02, 0x03 }, 0, 3); serialPortHelper.DataReceived += SerialPortHelper_DataReceived; serialPortHelper.ErrorReceived += SerialPortHelper_ErrorReceived; serialPortHelper.StartReading(); private void SerialPortHelper_DataReceived(byte[] buffer) { // 处理接收到的数据 } private void SerialPortHelper_ErrorReceived(SerialError eventType) { // 处理错误事件 } ``` 该辅助类提供了以下功能: - 连接与断开 - 写入数据 - 开始与停止读取数据 - 数据接收与错误事件的订阅 在使用时,可以根据需要订阅数据接收与错误事件,并调用Connect、Write、StartReading等方法。如果需要断开连接或停止读取数据,可以调用Disconnect或StopReading方法。如果出现错误,错误事件会被触发。在重连时,可以先调用Disconnect方法断开连接,再调用Connect方法重新连接

你可能感兴趣的:(c#,自动化)