<small id='NyxL8v'></small> <noframes id='RvSA6G9iC'>

  • <tfoot id='GTXg2Lli0'></tfoot>

      <legend id='eAsbf7S'><style id='dPMC'><dir id='pPVlf'><q id='fdKeW4'></q></dir></style></legend>
      <i id='zKi2htV'><tr id='0Ks4H'><dt id='NxFUIi'><q id='o7Dj'><span id='vOKNxp'><b id='u9YSs'><form id='QEdjVTl'><ins id='d2DE'></ins><ul id='E5r287'></ul><sub id='ZVEr'></sub></form><legend id='JYlzgAD1'></legend><bdo id='C90d6jV'><pre id='l5Vn'><center id='UBz4L0Y'></center></pre></bdo></b><th id='t4lwi'></th></span></q></dt></tr></i><div id='oECNJxZOl'><tfoot id='9WzchQ'></tfoot><dl id='AHmbv'><fieldset id='5e3KFd'></fieldset></dl></div>

          <bdo id='V9E0M7v'></bdo><ul id='0wVMvF'></ul>

          1. <li id='7CbwE'></li>
            登陆

            章鱼彩票鱼丸提现-C#串口操作类,包含串口读写操作

            admin 2019-05-31 222人围观 ,发现0个评论

            串口进行操作的类,其间包含写和读操作,类可设置串口参数、设置接纳函数、翻开串口资源、封闭串口资源,操作完成后,一定要封闭串口、接纳串口数据事情、接纳数据犯错事情、获取当时悉数串口、把字节型转化成十六进制字符串等功能。这个串口类现已过了调试,能够运用:

            using System;

            using System.Collections.Generic;

            using System.Text;

            using System.IO.Ports;

            using System.Globalization;

            namespace SerialClass

            {

            public class SerialClass

            {

            SerialPort _serialPort = null;

            //界说托付

            public delegate void SerialPortDataReceiveEventArgs(object sender, SerialDataReceivedEventArgs e, byte[] bits);

            //界说接纳数据事情

            public even章鱼彩票鱼丸提现-C#串口操作类,包含串口读写操作t SerialPortDataReceiveEventArgs DataReceived;

            //界说接纳过错事情

            //public event SerialErrorReceivedEventHandler Error;

            //接纳事情是否有用 false表明有用

            public bool ReceiveEventFlag = false;

            #region 获取串口名

            private string protName;

            public string PortName

            {

            get { return _serialPort.PortName; }

            set

            {

            _serialPort.PortName = value;

            protName = value;

            }

            }

            #endregion

            #region 获取比特率

            private int baudRate;

            public int BaudRate

            {

            get { return _serialPort.BaudRate; }

            set

            {

            _se章鱼彩票鱼丸提现-C#串口操作类,包含串口读写操作rialPort.BaudRate = value;

            baudRate = value;

            }

            }

            #endregion

            #region 默许结构函数

            ///

            /// 默许结构函数,操作COM1,速度为9600,没有奇偶校验,8位字节,中止位为1 "COM1", 9600, Parity.None, 8, StopBits.One

            ///

            public SerialClass()

            {

            _serialPort = new SerialPort();

            }

            #endregion

            #region 结构函数

            ///

            /// 结构函数,

            ///

            ///

            public SerialClass(string comPortName)

            {

            _serialPort = new SerialPort(comPortName);

            _serialPort.BaudRate = 9600;

            _serialPort.Parity = Parity.Even;

            _serialPort.DataBits = 8;

            _serialPort.StopBits = StopBits.One;

            _serialPort.Handshake = Handshake.None;

            _serialPort.RtsEnable = true;

            _serialPort.ReadTimeout = 2000;

            setSerialPort();

            }

            #endregion

            #region 结构函数,能够自界说串口的初始化参数

            ///

            /// 结构函数,能够自界说串口的初始化参数

            ///

            ///

            需求操作的COM口称号

            ///

            COM的速度

            ///

            奇偶校验位

            ///

            数据长度

            ///

            中止位

            public SerialClass(string comPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits)

            {

            _serialPort = new SerialPort(comPortName, baudRate, parity, dataBits, stopBits);

            _serialPort.RtsEnable = true; //主动恳求

            _serialPort.ReadTimeout = 3000;//超时

            setSerialPort();

            }

            #endregion

            #region 析构函数

            ///

            /// 析构函数,封闭串口

            ///

            ~SerialClass()

            {

            if (_serialPort.IsOpen)

            _serialPort.Close();

            }

            #endregion

            #region 设置串口参数

            ///

            /// 设置串口参数

            ///

            ///

            需求操作的COM口称号

            ///

            COM的速度

            ///

            数据长度

            ///

            中止位

            public void setSerialPort(string comPortName, int baudRate, int dataBits, int stopBits )

            {

            if (_serialPort.IsOpen)

            _serialPort.Close();

            _serialPort.PortName = comPortName;

            _serialPort.BaudRate = baudRate;

            _serialPort.Parity = Parity.None;

            _serialPort.DataBits = dataBits;

            _serialPort.StopBits = (StopBits)stopBits;

            _serialPort.Handshake = Handshake.None;

            _serialPort.RtsEnable = false;

            _serialPort.ReadTimeout = 3000;

            _serialPort.NewLine = "/r/n";

            setSerialPort();

            }

            #endregion

            #region 设置接纳函数

            ///

            /// 设置串口资源,还需重载多个设置串口的函数

            ///

            void setSerialPort()

            {

            if (_serialPort != null)

            {

            //设置触发DataReceived事情的字节数为1

            _serialPort.ReceivedBytesThreshold = 1;

            //接纳到一个字节时,也会触发DataReceived事情

            _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

            //接纳数据犯错,触发事情

            _serialPort.ErrorReceived += new SerialErrorReceivedEventHandler(_serialPort_ErrorReceived);

            //翻开串口

            //openPort();

            }

            }

            #endregion

            #region 翻开串口资源

            ///

            /// 翻开串口资源

            /// 回来bool类型

            ///

            public bool openPort()

            {

            bool ok = false;

            //假如串口是翻开的,先封闭

            if (_serialPort.IsOpen)

            _serialPort.Close();

            try

            {

            //翻开串口

            _serialPort.Open();

            ok = true;

            }

            catch (Exception Ex)

            {

            throw Ex;

            }

            return ok;

            }

            #endregion

            #region 封闭串口

            ///

            /// 封闭串口资源,操作完成后,一定要封闭串口

            ///

            public void closePort()

            {

            //假如串口处于翻开状况,则封闭

            if (_serialPort.IsOpen)

            _serialPort.Close();

            }

            #endregion

            #region 接纳串口数据事情

            ///

            /// 接纳串口数据事情

            ///

            ///

            ///

            void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

            {

            //制止接纳事情时直接退出

            if (ReceiveEventFlag)

            {

            return;

            }

            try

            {

            System.Threading.Thread.Sleep(20);

            byte[] _data = new byte[_serialPort.BytesToRead];

            _serialPort.Read(_data, 0, _data.Length);

            if (_data.Length == 0) { return; }

            if (DataReceived != null)

            {

            DataReceived(sender, e, _data);

            }

            //_serialPort.DiscardInBuffer(); //清空接纳缓冲区

            }

            catch (Exception ex)

            {

            throw ex;

            }

            }

            #endregion

            #region 接纳数据犯错事情

            ///

            /// 接纳数据犯错事情

            ///

            ///

            ///

            void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)

            {

            }

            #endregion

            #region 发送数据string类型

            public void SendData(string data)

            {

            //发送数据

            //制止接纳事情时直接退出

            if (ReceiveEventFlag)

            {

            return;

            }

            if (_serialPort.IsOpen)

            {

            _serialPort.Write(data);

            }

            }

            #endregion

            #region 发送数据byte类型

            ///

            /// 数据发送

            ///

            ///

            要发送的数据字节

            public void SendData(byte[] data, int offset, int count)

            {

            //制止接纳事情时直接退出

            if (ReceiveEventFlag)

            {

            return;

            }

            try

            {

            if (_serialPort.IsOpen)

            {

            //_serialPort.DiscardInBuffer();//清空接纳缓冲区

            _serialPort.Write(data, offset, count);

            }

            }

            catch (Exception ex)

            {

            throw ex大王乌贼;

            }

            }

            #endregion

            #region 发送指令

            ///

            /// 发送指令

            ///

            ///

            发送数据

            ///

            接纳数据

            ///

            超时时刻

            ///

            public int SendCommand(byte[] SendData, ref byte[]章鱼彩票鱼丸提现-C#串口操作类,包含串口读写操作 ReceiveData, int Overtime)

            {

            if (_serialPort.IsOpen)

            {

            try

            {

            ReceiveEventFlag = true; //封闭接纳事情

            _serialPort.DiscardInBuffer(); //清空接纳缓冲区

            _serialPort.Write(SendData, 0, SendData.Length);

            int num = 0, ret = 0;

            System.Threading.Thread.Sleep(10);

            ReceiveEventFlag = false; //翻开事情

            while (num++ < Overtime)

            {

            if (_serialPort.BytesToRead >= ReceiveData.Length)

            break;

            System.Threading.Thread.Sleep(10);

            }

            if (_serialPort.BytesToRead >= ReceiveData.Length)

            {

            ret = _serialPort.Read(ReceiveData, 0, ReceiveData.Length);

            }

            else

            {

            ret = _serialPort.Read(ReceiveData, 0, _serialPort.BytesToRead);

            }

            ReceiveEventFlag = false; //翻开事情

            return ret;

            }

            catch (Exception ex)

            {

            ReceiveEventFlag = false;

            throw ex;

            }

            }

            return -1;

            }

            #endregion

            #region 获取串口

            ///

            /// 获取一切已衔接短信猫设备的串口

            ///

            ///

            public string[] serialsIsConnected()

            {

            List lists = new List();

            string[] seriallist = getSerials();

            foreach (string s in seriallist)

            {

            }

            return lists.ToArray();

            }

            #endregion

            #region 获取当时悉数串口资源

            ///

            /// 取得当时电脑上的一切串口资源

            ///

            ///

            public string[] getSerials()

            {

            return SerialPort.GetPortNames();

            }

            #endregion

            #region 字节型转化16

            ///

            /// 把字节型转化成十六进制字符串

            ///

            ///

            ///

            public static string ByteToString(byte[] InBytes)

            {

            string StringOut = "";

            foreach (byte InByte in InBytes)

            {

            StringOut = StringOut + String.Format("{0:X2} ", InByte);

            }

            return StringOut;

            }

            #endregion

            #region 十六进制字符串转字节型

            ///

            /// 把十六进制字符串转化成字节型(办法1)

            ///

            ///

            ///

            public static byte[] StringToByte(string InString)

            {

            string[] ByteStrings;

            ByteStrings = InString.Split(" ".ToCharArray());

            byte[] ByteOut;

            ByteOut = new byte[ByteStrings.Length];

            for (int i = 0; i <= ByteStrings.Length-1 ; i++)

            {

            //ByteOut[i] = System.Text.Encoding.ASCII.GetBytes(ByteStrings[i]);

            ByteOut[i] = Byte.Parse(ByteStrings[i], System.Globalization.NumberStyles.HexNumber);

            //ByteOut[i] =Convert.ToByte("0x" + ByteStrings[i]);

            }

            return ByteOut;

            }

            #endregion

            #region 十六进制字符串转字节型

            ///

            /// 字符串转16进制字节数组(办法2)

            ///

            ///

            ///

            public static byte[] strToToHexByte(string hexString)

            {

            hexString = hexString.Replace(" ", "");

            if ((hexString.Length % 2) != 0)

            hexString += " ";

            byte[] returnBytes = new byte[hexString.Length / 2];

            for (int i = 0; i < returnBytes.Length; i++)

            returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);

            return returnBytes;

            }

            #endregion

            #region 字节型转十六进制字符串

            ///

            /// 字节数组转16进制字符串

            ///

            ///

            ///

            public static string byteToHexStr(byte[] bytes)

            {

            string returnStr = "";

            if (bytes != null)

            {

            for (int i = 0; i < bytes.Length; i++)

            {

            returnStr += bytes[i].ToString("X2");

            }

            }

            return returnStr;

            }

            #endregion

            }

            }

            ======================================================================================

            调用办法:

            static SerialClass sc = new SerialClass();

            static void Main(string[] Args)

            {

            sc.DataReceived += new SerialClass.SerialPortDataReceiveEventArgs(sc_DataReceived);

            sc.writeData("at");

            Console.ReadLine();

            sc.closePort();

            }

            static void sc_DataReceived(object sender, SerialDataReceivedEventArgs e, byte[] bits)

            {

            Console.WriteLine(Encoding.Default.GetString(bits));

            }

            请关注微信公众号
            微信二维码
            不容错过
            Powered By Z-BlogPHP