C#实现串口通讯

B站影视 2024-12-22 21:27 2

摘要:SerialPort serialClient;StopBits stopBits = StopBits.One;Parity parity = Parity.None;//打开串口public void TurnOn{ if (serialClient !=

一、引用dll

using System.IO.Ports;

二、串口连接

SerialPort serialClient;StopBits stopBits = StopBits.One;Parity parity = Parity.None;//打开串口public void TurnOn{ if (serialClient != null) { serialClient.Close; } serialClient = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One); serialClient.DataReceived += SerialClient_DataReceived; serialClient.Open;}//关闭串口public void TurnOff{ try { serialClient.Close; } catch (Exception) { }}

三、接收数据

/// /// 串口接收数据事件/// ///

///

private void SerialClient_DataReceived(object sender, SerialDataReceivedEventArgs e){ try { byte buffer; int num = serialClient.BytesToRead; // 接收到的byte数 if (num == 0) { return; } buffer = new byte[num]; //解析数据 string readString = System.Text.Encoding.Default.GetString(buffer, 0, buffer.Length); } catch (Exception) { }}

来源:上位机李工

相关推荐