using System; using System.Collections.Generic; using System.IO.Ports; using System.Text; //串口通訊類 public class SerialPortManager { //聲明一個靜態的串口資源 priva ...
using System; using System.Collections.Generic; using System.IO.Ports; using System.Text; //串口通訊類 public class SerialPortManager { //聲明一個靜態的串口資源 private SerialPort ComDevice = new SerialPort(); public SerialPortManager() { var portList = SerialPort.GetPortNames();//獲取當前搜索到的串口集合 ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived); //綁定事件,接收到串口數據時觸發 } /// <summary> /// 打開和關閉串口, /// 前端放個按鈕調用這個方法 /// 串口名稱用SerialPort.GetPortNames()拉取所有串口,上面構造有寫 /// 下麵相關的參數具體有些哪些百度下就知道了,這塊只是舉例,當然也可以直接用 /// </summary> /// <param name="serialPortName">串口名稱</param> /// <returns></returns> public void openOrCloseSerialPort(string serialPortName) { //判斷當前狀態是打開還是關閉,開啟的話就關閉,反之就開啟 if (ComDevice.IsOpen == false) { //設置串口名稱 ComDevice.PortName = serialPortName; //設置波特率 ComDevice.BaudRate = 115200; //設置數據位 ComDevice.DataBits = 8; //校驗位設置 ComDevice.StopBits = StopBits.One; //停止位設置 ComDevice.Parity = Parity.None; //開啟串口 ComDevice.Open(); } else { ComDevice.Close();//關閉串口 } } /// <summary> /// 串口數據讀取方法,在構造時已經監聽 /// </summary> private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] ReDatas = new byte[ComDevice.BytesToRead]; ComDevice.Read(ReDatas, 0, ReDatas.Length); //接收到的位元組流 var data = ReDatas; //根據自己需求轉換 var str = new UTF8Encoding().GetString(ReDatas); } /// <summary> /// 發送數據方法 /// </summary> /// <param name="data">需要發送的位元組流</param> public void Com_SendData(byte[] data) { if (ComDevice.IsOpen) { ComDevice.Write(data, 0, data.Length);//發送數據 } } }