C# WPF 基于SerialPort类实现串口通信,打开、关闭、接收、发送,支持HEX数据和ASCII数据收发。

  • 纯小白教程,串口通信,实例自定义类,调用方法即可使用,可自己加定时器实现自动发送。

  • 后端.xmal.cs

 public partial class MainWindow : Window
 {
     public MainWindow()
        {
            InitializeComponent();
            SerialPortInit();
        }

     private CsSerialPort mySerialPort = new CsMySerialPort();
     private CsSerialPort.SerialPortParm SpParm = new CsSerialPort.SerialPortParm()
        {
            strPortName = "COM1",
            strBaudRate = "115200",
            strDataBits = "8",
            strStopBits = "1",
            strParity = "0",

            nReceType = CsSerialPort.ReceType.HEX,
            nByteCnt = 10,
        };
     private void SerialPortInit()
        {
            mySerialPort.SendBuffer+= ReceDataClick;//只接收byte[] 类型
        }

     private viod ReceSerialPort(byte[] bufIn)
        {
            var strCompare = bufIn;    
        }
 
     private void BtTxSend_Click(object sender, RoutedEventArgs e) => mySerialPort.ComSend(输入类型是Byte[] 或者 string,看你初始化选择的模式);

     private void BtConnect_Click(object sender, RoutedEventArgs e) => mySerialPort.OpenSerialPort(SpParm);

     private void BtBreak_Click(object sender, RoutedEventArgs e) => mySerialPort.CloseSerialPort();
 }

  • 基于SerialPort类自定义的串口类
    public class CsSerialPort
    {
        /// <summary>
        /// 作者:WangJunLiang || Wechat:Joronwongx
        /// </summary>

        //初始化
        public struct SerialPortParm
        {
            public ReceType nReceType;       //0-HEX 1-String
            public int nByteCnt;        //字节数
            public string strEnd;       //结尾字符

            public string strPortName;  //eg:COM1
            public string strBaudRate;  //eg:9600
            public string strDataBits;  //eg:8

            public string strStopBits;  //eg:1
            public string strParity;    //eg:0
            public StopBits GetStopBits()
            {
                StopBits stopBits = StopBits.One;
                switch (strStopBits)
                {
                    case "1": stopBits = StopBits.One; break;
                    case "2": stopBits = StopBits.Two; break;
                    case "1.5": stopBits = StopBits.OnePointFive; break;
                    default: break;
                }
                return stopBits;
            }
            public Parity GetParity()
            {
                Parity parity = Parity.None;
                switch (strParity)
                {
                    case "0": parity = Parity.None; break;
                    case "1": parity = Parity.Odd; break;
                    case "2": parity = Parity.Even; break;
                    default: break;
                }
                return parity;
            }
        }

        public enum ReceType : int
        {
            HEX = 0,
            String = 1,
        }

        #region 接收实现 并回调

        private ReceType m_nReceType;//0-HEX 1-String
        private int m_nByteCnt;//字节数
        public string m_strEnd;//结尾字符

        private void SerialPortReceDataClick(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                switch (m_nReceType)
                {
                    case ReceType.HEX: ReceHEX(); break;
                    case ReceType.String: ReceString(); break;
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }

        private void ReceHEX()
        {
            int nReceCnt = 0;
            byte[] Readbuffer = new byte[m_nByteCnt];
            while (nReceCnt < m_nByteCnt)
            {
                int nRead = SPserialPort.Read(Readbuffer, nReceCnt, m_nByteCnt - nReceCnt);
                nReceCnt += nRead;
            }
            if (Readbuffer[0] == 0xa5 && Readbuffer[1] == 0x24)
                SendBuffer(Readbuffer);//向数据Model发送内容
            else
                SPserialPort.DiscardInBuffer();
        }

        private void ReceString()
        {
            string strReceData = SPserialPort.ReadTo(m_strEnd);
            SendString(strReceData);
        }

        public delegate void SendHEXData(byte[] bufSend);
        public event SendHEXData SendBuffer;

        public delegate void SendStringData(string strSend);
        public event SendStringData SendString;

        #endregion

        #region 打开/关闭实现

        private SerialPort SPserialPort = null;

        public bool OpenSerialPort(SerialPortParm parm)
        {
            try
            {
                if (SPserialPort != null)
                    return false;
                SPserialPort = new SerialPort
                {
                    PortName = parm.strPortName,
                    BaudRate = int.Parse(parm.strBaudRate),
                    DataBits = int.Parse(parm.strDataBits),
                    StopBits = parm.GetStopBits(),
                    Parity = parm.GetParity(),

                    WriteBufferSize = 1048576,
                    ReadBufferSize = 2097152,
                    Encoding = System.Text.Encoding.GetEncoding("UTF-8"),
                    Handshake = Handshake.None,
                    RtsEnable = true
                };
                m_nReceType = parm.nReceType;
                m_nByteCnt = parm.nByteCnt;
                m_strEnd = parm.strEnd;
                SPserialPort.DataReceived += new SerialDataReceivedEventHandler(SerialPortReceDataClick);//接收响应函数

                SPserialPort.Open();
                return true;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public bool CloseSerialPort()
        {
            try
            {
                if (SPserialPort != null && SPserialPort.IsOpen)
                {
                    SPserialPort.Close();
                    SPserialPort = null;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }

        #endregion

        #region  发送实现 

        public bool ComSend(byte[] decBytes)
        {
            try
            {
                if (SPserialPort != null && SPserialPort.IsOpen)
                {
                    SPserialPort.Write(decBytes, 0, decBytes.Length);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }

        public bool ComSend(string strIn)
        {
            try
            {
                if (SPserialPort != null && SPserialPort.IsOpen)
                {
                    //SPserialPort.Write(strIn.ToCharArray(), 0, strIn.Length); /* ASCII字符串发送 */
                    SPserialPort.Write(strIn);
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                return false;
            }
        }
        #endregion
    }


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页