WPF 初始化串口 接收和发送串口数据

  • Post author:
  • Post category:其他


提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档



一、直接在后端初始化串口,接收串口数据,发送串口数据

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



        public SerialPort serialPort5;
        private void getScan5()
        {
            serialPort5 = new SerialPort();
            if (serialPort5 != null && serialPort5.IsOpen)
            {
                MessageBox.Show("串口" + serialPort5.PortName + " 波特率:" + serialPort5.BaudRate + "已被占用,不能重复打开!");
                return;
            }
            serialPort5 = new SerialPort();
            serialPort5.PortName = "";
            serialPort5.BaudRate = 9600;
            serialPort5.Parity = Parity.None;   //异或校验为偶校验
            serialPort5.DataBits = 8;   //每个字节8位数据
            serialPort5.StopBits = StopBits.One;    //使用一个停止位
            try
            {
                serialPort5.Open();
            }
            catch (Exception ex)
            {
                if (ex.Message == "对端口“" + serialPort5.PortName + "”的访问被拒绝。")
                {
                    MessageBox.Show(serialPort5.PortName + "可能已经打开,请核实!");
                    return;
                }
            }
            if (serialPort5.IsOpen)
            {
                MessageBox.Show("串口打开成功!\r\n串口号:" + serialPort5.PortName + " 波特率:" + serialPort5.BaudRate);
            }
            else
            {
                MessageBox.Show("串口配置失败");
            }
            serialPort5.DataReceived += new SerialDataReceivedEventHandler(Sp_DataReceived5);
        }

        List<byte> bufData5 = new List<byte>(4096);
        byte[] bufByteRcv5 = new byte[13];
        public void Sp_DataReceived5(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            SerialPort serialPort = (SerialPort)(sender);
            Console.WriteLine(serialPort.PortName);
            System.Threading.Thread.Sleep(50);//延缓一会,用于防止硬件发送速率跟不上缓存数据导致的缓存数据杂乱
            int n = serialPort.BytesToRead;//先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致  
            byte[] buf = new byte[n];//声明一个临时数组存储当前来的串口数据  
            serialPort.Read(buf, 0, n);//读取缓冲数据
            bufData5.AddRange(buf);
            try
            {
                bufData5.CopyTo(0, bufByteRcv5, 0, 13);               //将bufData5中的数据储存进bufByteRcv[]中
                bufData5.Clear();
                string streamCode = Encoding.ASCII.GetString(bufByteRcv5, 0, bufByteRcv5.Length);
                Console.WriteLine(streamCode);
                //页面文本框赋值显示
                if (streamCode.Length == 13)
                {

                }

            }
            catch (Exception ex)
            {
            }
        }



        private void sendNews()
        {
            byte[] sendBytes = getSendBytes("12345645646456");
            serialPort5.Write(sendBytes, 0, sendBytes.Length);//串口发送字节数组数据
        }
        private byte[] getSendBytes(string lightCode)
        {
            string code = getSerialPortSendStr(lightCode);
            byte[] sendBytes = HexStrToByteArray(code);//将16进制的字符串数据转换为字节数组
            return sendBytes;
        }
        /// <summary>
        /// 将16进制的字符串数据转换为字节数组
        /// </summary>
        /// <param name="hexString">16进制的字符转数据 e.g:7e 7e 12 00 01 01 00 02 0a .... f5</param>
        /// <returns>返回字节数组,类型为byte[]</returns>
        public static byte[] HexStrToByteArray(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += "0";
            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;
        }
        // 将亮灯编码和其他数据位连接起来,然后组合为完整的35位16进制数据字符串
        private string getSerialPortSendStr(string lightCodeStr)
        {

            string code = "7e 7e 10 00 00 00 ";
            code += Convert.ToInt32(lightCodeStr.Substring(0, 2)).ToString("X2");
            code += " ";
            code += Convert.ToInt32(lightCodeStr.Substring(2, 2)).ToString("X2");
            code += " 0a 00 16 13 15 00 03 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00";
            string checkStr = Get_CheckXorTest(code);//通过对前33位进行的异或运算得到第34位(倒数第二位)异或校验位
            code += " ";
            code += checkStr;
            code += " f5";
            return code;
        }
        /// <summary> 
        /// 将16进制字符串转换为字节数组,然后进行异或运算,将计算结果转换为16进制返回
        /// </summary>
        /// <param name="str">e.g: 7e 7e 12 00 00 00 00 02 0a 00 16 00 15 10 00 00 00 00 01 00 00 00 01 00 01 03 00 00 00 00 00 00 00</param>
        /// <returns>返回计算出的校验位,e.g: 1D</returns>
        public string Get_CheckXorTest(string str)
        {
            string[] array = str.Split(' ');
            byte[] byteArray = new byte[array.Length];
            for (int i = 0; i < array.Length; i++)
            {
                byteArray[i] = Convert.ToByte(array[i], 16);//将16进制数据转换为8位的无符号整数(然后放到字节数组中)
            }
            byte a = Get_CheckXor(byteArray);
            //string b = a.ToString("X");//将a(8位的无符号整数)转为16进制
            string b = a.ToString("X").PadLeft(2, '0');//将a(8位的无符号整数)转为16进制
            return b;
        }

        // <summary>
        /// 将字节数组逐位进行异或运算
        /// </summary>
        /// <param name="data">需要进行运算的字节数组</param>
        /// <returns>返回运算结果,为二进制数据</returns>
        public byte Get_CheckXor(byte[] data)
        {
            byte CheckCode = 0;
            for (int i = 0; i < data.Length; i++)
            {
                CheckCode ^= data[i];
            }
            return CheckCode;
        }

    }





版权声明:本文为Zzu_zzx原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。