c#串口通信类代码可以直接调用

Posted HarleyGwak

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#串口通信类代码可以直接调用相关的知识,希望对你有一定的参考价值。

文章首发于浩瀚先森博客

直接上代码

public struct SerialPara
    {
        private string portName;
        public string PortNameSetGet
        {
            get { return portName; }
            set { portName = value; }
        }

        private int baudRate;
        public int BaudRateSetGet
        {
            get { return baudRate; }
            set { baudRate = value; }
        }

        private Parity parity;
        public Parity ParitySetGet
        {
            get { return parity; }
            set { parity = value; }
        }

        private int databit;
        public int DatabitSetGet
        {
            get { return databit; }
            set { databit = value; }
        }

        private StopBits stopBits;
        public StopBits StopBitsSetGet
        {
            get { return stopBits; }
            set { stopBits = value; }
        }
    }

    public class SerialCommClass
    {
        SerialPara sp;
        public SerialCommClass(SerialPara sp_temp)
        {
            this.sp = new SerialPara();
            sp.PortNameSetGet = sp_temp.PortNameSetGet;
            sp.BaudRateSetGet = sp_temp.BaudRateSetGet;
            sp.ParitySetGet = sp_temp.ParitySetGet;
            sp.DatabitSetGet = sp_temp.DatabitSetGet;
            sp.StopBitsSetGet = sp_temp.StopBitsSetGet;
        }

        public bool Serial_Connect(ref SerialPort serialPort)
        {
            /*check serial parameter*/
            if(!checkSerialPara(this.sp))
                return false;
            
            /*Serial Port configuration*/
            serialPort.PortName = sp.PortNameSetGet;
            serialPort.BaudRate = sp.BaudRateSetGet;
            serialPort.DataBits = sp.DatabitSetGet;
            serialPort.Parity = sp.ParitySetGet;
            serialPort.StopBits = sp.StopBitsSetGet;

            try
            {
                serialPort.Open();
            }
            catch (Exception exc)
            {
                return false;
            }
            return true;
        }

        //发送字符串数据    
        public bool SendStringData(ref SerialPort serialPort,string data)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Write(data);
                return true;
            }
            else
            {
                return false;
            }
        }
        
        //发送二进制数据    
        public string SendBytesData(ref SerialPort serialPort, string data)
        {
            //byte[] bytesSend = System.Text.Encoding.Default.GetBytes(data);
            byte[] bytesSend = strToToHexByte(data);
            if (bytesSend == null)
                return null;
            try
            {
                serialPort.Write(bytesSend, 0, bytesSend.Length);
                return bytesSend.Length + "";
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /*check serial parameter*/
        private bool checkSerialPara(SerialPara sp)
        {
            if(sp.PortNameSetGet==null)
               return false;
            return true;
        }

        /// <summary> 
        /// 字符串转16进制字节数组 
        /// </summary> 
        /// <param name="hexString"></param> 
        /// <returns></returns> 
        private static byte[] strToToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if (hexString.Substring(0, 2) == "0x" || hexString.Substring(0, 2) == "0X")
                hexString = hexString.Substring(2, hexString.Length - 2);
            byte[] returnBytes = new byte[hexString.Length / 2];
            try
            {
                for (int i = 0; i < returnBytes.Length; i++)
                    returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
                    //returnBytes[returnBytes.Length - i - 1] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            catch (Exception e)
            {
                return null;
            }
            return returnBytes;
        } 
    }

以上是关于c#串口通信类代码可以直接调用的主要内容,如果未能解决你的问题,请参考以下文章

C#异步数据接收串口操作类

c#串口测试

C#做一个简单的进行串口通信的上位机

C#串口介绍及串口通信程序设计实现(附程序分享)

C#中显现串口通信SerialPort类

51单片机上位机编写与串口通信-深入了解串口