C#完成串口通讯工具的编写

串口通讯上位机的组成

  1. 连接功能
  2. 发送功能
  3. 接收功能
    *只要是完成这三个功能那么说咱们的上位机已经可以实现功能了,那么怎么去实现这三个功能呢?
    第一个连接:
    波特率、停止位、*端口名、数据位、校验位

获取端口

 private void PortcomboBox_DropDown(object sender, EventArgs e)
        {
            PortcomboBox.Items.Clear();
            List<string> SystemPortsList = new List<string>(SerialPort.GetPortNames());
            List<string> AddList = new List<string();
             foreach (string item in SystemPortsList)
            {
                if (!AddList.Contains(item))
                {
                    AddList.Add(item);
                }
            }
             Comparison<string> comparer = delegate (string name1, string name2)
            {
                int port1 = Convert.ToInt32(name1.Remove(0, 3));
                int port2 = Convert.ToInt32(name2.Remove(0, 3));
                return port1 - port2;
            };
            AddList.Sort(comparer);
            PortcomboBox.Items.AddRange(AddList.ToArray());
        }

连接

 private void bt_openPort_Click(object sender, EventArgs e)
        {
            if (bt_openPort.Text.Equals("打开串口"))
            {
                try
                {
                    serialPort.PortName = PortcomboBox.Text;
                    serialPort.BaudRate = Convert.ToInt32(BaudRatecomboBox.Text);
                    serialPort.DataBits = Convert.ToInt32(DataBitscomboBox.Text);
                     if (ParityBitcomboBox.SelectedIndex == 0)
                        serialPort.Parity = System.IO.Ports.Parity.None;
                    else if (ParityBitcomboBox.SelectedIndex == 1)
                        serialPort.Parity = System.IO.Ports.Parity.Odd;
                    else if (ParityBitcomboBox.SelectedIndex == 2)
                        serialPort.Parity = System.IO.Ports.Parity.Even;
                    if (StopBitscomboBox.SelectedIndex == 0)
                       serialPort.StopBits = System.IO.Ports.StopBits.One;
                    else if (StopBitscomboBox.SelectedIndex == 1)
                        serialPort.StopBits = System.IO.Ports.StopBits.OnePointFive;
                     else if (StopBitscomboBox.SelectedIndex == 2)
                        serialPort.StopBits = System.IO.Ports.StopBits.Two;
                    //设置奇偶校验错误代替字节
                    byte b = (byte)'\0';
                    serialPort.ParityReplace = b;
                    //打开串口
                    serialPort.Open();
                    //combox禁止改变
                    BaudRatecomboBox.Enabled = false;
                    ParityBitcomboBox.Enabled = false;
           		    DataBitscomboBox.Enabled = false;
                    StopBitscomboBox.Enabled = false;
                    PortcomboBox.Enabled = false;
                    bt_openPort.Text = "关闭串口";
                     }
                catch
                {
                    MessageBox.Show("端口不存在或被占用", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
             else
            {
                try
                {
                    serialPort.Close();
                    BaudRatecomboBox.Enabled = true;
                    ParityBitcomboBox.Enabled = true;
                    DataBitscomboBox.Enabled = true;
                    StopBitscomboBox.Enabled = true;
                    PortcomboBox.Enabled = true;
                    bt_openPort.Text = "打开串口";
                }
                 catch (Exception e1)
                {
                    MessageBox.Show("关闭串口出错,原因" + e1.ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

发送

 public void Writemessage(string str)
        {
            byte[] send = Util.HEXstring_to_bytys(str);//将字符串转换为字节数组
            serialPort.Write(send, 0, send.Length);
        }

接收

 //串口接收
        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            //端口缓冲区字节数
            int n = serialPort.BytesToRead;
            //  Console.WriteLine(n);
           //将端口缓冲区数据存入字节数组
            byte[] byteRev = new byte[n];
            serialPort.Read(byteRev, 0, n);
            //将字节数组存入程序缓冲区
            string data = "";
            for (int i = 0; i < n; i++)
            {
               data += byteRev[i].ToString("X2");
            }
            RXbuffer += data;
        }

缓冲设置

 public string RecieveMessage(int timeout)
        {
            string str = RXbuffer;
            Thread.Sleep(60);
            for (int i = 0; i < 40; i++)
            {
                if(RXbuffer.Length==0)
                {
                    Thread.Sleep(60);
                    continue;
                }
                if (RXbuffer.Length > str.Length)
                {
                    str = RXbuffer;
                    Thread.Sleep(60);
                }
                 else
                    break;
            }

            return RXbuffer;
        }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值