2020-05-04

C#串口通讯,复制粘贴就可用,仅仅介绍怎样最快的搭建一个串口通讯,异常拦截等等需要自己加上

C#串口通讯,复制粘贴就可用,仅仅介绍怎样最快的搭建一个串口通讯,异常拦截等等需要自己加上


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);//发送数据  } }}

 


No comments:

Post a Comment