C#WinForm realizes serial communication

   Serial port communication is a common data transmission method for computers.

   The program runs as follows:

  First, check the computer's serial port and get all the serial port information.

        private void CheckPort()//检查串口是否可用
        {
            myLog(2, "检测串口开始!");  //log记录函数
            comboBox1.Items.Clear();//清除控件中的当前值         
            string[] a = SerialPort.GetPortNames();
            if (a.Length != 0)
            {
                for (int i = 0; i < a.Length; i++)
                {
                    comboBox1.Items.Add(a[i]);
                }
                comboBox1.SelectedIndex = 0;//??
                myLog(2, "检测串口完成");
            }
            else
            {
                myLog(2, "无可用串口...", true);
            }
        }
        private void SetPort()//设置串口
        {
            try
            {
                serialPort1.PortName = comboBox1.Text.Trim();//串口名给了串口类
                //波特率   虚拟串口的波特率好像不能修改,但得将其赋为空,不然报错         
                // serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text.ToString().Trim());        
                // 9600;
                serialPort1.BaudRate = Convert.ToInt32("".Trim());
                //奇偶效验
                if (comboBox5.Text.Trim() == "奇校验")
                {
                    serialPort1.Parity = Parity.Odd;//将奇校验位给了sp的协议
                }
                else if (comboBox5.Text.Trim() == "偶校验")
                {
                    serialPort1.Parity = Parity.Even;
                }
                else
                {
                    serialPort1.Parity = Parity.None;
                }
                //停止位
                if (comboBox4.Text.Trim() == "1.5")
                {
                    serialPort1.StopBits = StopBits.OnePointFive;//设置停止位有几位
                }
                else if (comboBox4.Text.Trim() == "2")
                {
                    serialPort1.StopBits = StopBits.Two;
                }
                else
                {
                    serialPort1.StopBits = StopBits.One;
                }
                serialPort1.DataBits = Convert.ToInt16(comboBox3.Text.ToString().Trim());//数据位
                serialPort1.Encoding = Encoding.UTF8;//串口通信的编码格式
                serialPort1.Open();
            }
            catch { }
        }
        /// <summary>
        /// Log记录
        /// </summary>
        /// <param name="aa">aa=  0为发送  1为接受 2为日常记录</param>
        /// <param name="mystr">记录内容</param>
        /// <param name="IsHint">true 显示弹框,false 不显示弹框 默认false</param>
        private void myLog(int aa, string mystr, bool IsHint = false)
        {
            //log存放路径
            string myypath = myPath + DateTime.Now.ToString("yyyyMMdd") + ".txt";
            StreamWriter sw = new StreamWriter(myypath, true);
            string tempSendstr;
            if (aa == 0)
            {
                tempSendstr = DateTime.Now.ToString("HH:mm:ss.fff") + "  " + serialPort1.PortName + " 发送--->>>  " + mystr;
            }
            else if (aa == 1)
            {
                tempSendstr = DateTime.Now.ToString("HH:mm:ss.fff") + "  " + serialPort1.PortName + " 接收<<<---  " + mystr;
            }
            else
            {
                tempSendstr = DateTime.Now.ToString("HH:mm:ss.fff") + "  " + mystr;
            }
            sw.WriteLine(tempSendstr);
            sw.Close();
            //弹框提示
            if (IsHint)
            {
                MessageBox.Show(mystr, "提示");
            }
            if (listBox1.Items.Count >= 10) listBox1.Items.Clear();
            listBox1.Items.Add(tempSendstr);
        }

    Most notebooks do not have serial ports, we can download Configure Virtual Serial Port Driver from the Internet, add several pairs of virtual serial ports to our notebooks (virtual serial ports are paired and matched one by one), and then use the serial port debugging assistant to Ready for debugging.

    Data sending:

       //发送
        private void button3_Click(object sender, EventArgs e)
        {
            if(!serialPort1.IsOpen)
            {
                MessageBox.Show("串口未打开,请检查!");
                return;
            }
            string mystr1 = textBox1.Text;
            byte[] a = Encoding.UTF8.GetBytes(mystr1);
            string mystr2 = Encoding.UTF8.GetString(a);
            serialPort1.Write(mystr2);//将数据写入串行端口输出缓冲区
            myLog(0, mystr2);
        }

Data reception:

      //串口接收数据
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(100);
            this.Invoke((EventHandler)(delegate //异步委托一个线程
            {
                if (serialPort1.BytesToRead > 0)
                {
                    byte[] a = new byte[serialPort1.BytesToRead];//读出缓冲区串口通信的字节                                              
                    int readbytes = 0;
                    while (serialPort1.Read(a, readbytes, serialPort1.BytesToRead - readbytes) <= 0) ;
                    string str = UTF8Encoding.UTF8.GetString(a);
                    textBox2.Text = str + "\r\n";
                    myLog(1, str);
                }
            }));
        }

This is the sending and receiving of strings between serial ports. If you want to transmit hexadecimal, you only need to convert the string into hexadecimal when sending and receiving data, and then write it into the buffer or read it.

When multiple messages are sent, the following situations may occur.

The serial port debugging assistant reads out the data sent three times together. At this time, we only need to give a certain delay when sending.

In this way, the sending and receiving of multiple pieces of information on the serial port can be realized.

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/Iawfy_/article/details/116781212