c#串口通訊並處理接收的多個參數

最近摸索作個上位機,簡單記錄一下關鍵的幾個部分html

c#作串口通訊主要使用的是System.IO.Ports類,其實仍是十分方便的
最終效果以下:

千萬不要忘記了下面這個
c#

填寫串口相關配置

咱們能夠經過GetPortNames方法獲取本機的端口列表,注意:不一樣設備鏈接電腦後端口不必定相同後端

string[] sps = SerialPort.GetPortNames();

配置其餘串口相關
例如波特率列表數組

string[] baud = { "300", "1200", "2400", "4800", "9600", "19200", "38400", "57600" };
comboBox2.Items.AddRange(baud);     //添加波特率列表

打開串口

其實主要就是用當前串口屬性判斷是不是打開狀態緩存

private void Button1_Click(object sender, EventArgs e)
        {
            //trycatcj處理串口打開過程當中的異常
            try
            {
                //將可能產生異常的代碼放置在try塊中
                //根據當前串口屬性來判斷是否打開
                if (serialPort1.IsOpen)
                {
                    //串口已經處於打開狀態
                    serialPort1.Close();    //關閉串口
                    button1.Text = "打開串口";
                    button1.BackColor = Color.ForestGreen;
                    comboBox1.Enabled = true;
                    comboBox2.Enabled = true;
                    comboBox3.Enabled = true;
                    comboBox4.Enabled = true;
                    comboBox5.Enabled = true;
                   ReceptTb.Text = "";  //清空接收區
                    SendTb.Text = "";     //清空發送區
                }
                else
                {
                    //串口已經處於關閉狀態,則設置好串口屬性後打開
                    comboBox1.Enabled = false;
                    comboBox2.Enabled = false;
                    comboBox3.Enabled = false;
                    comboBox4.Enabled = false;
                    comboBox5.Enabled = false;
                    serialPort1.PortName = comboBox1.Text;
                    serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
                    serialPort1.DataBits = Convert.ToInt16(comboBox3.Text);

                    if (comboBox4.Text.Equals("None"))
                        serialPort1.Parity = System.IO.Ports.Parity.None;
                    else if (comboBox4.Text.Equals("Odd"))
                        serialPort1.Parity = System.IO.Ports.Parity.Odd;
                    else if (comboBox4.Text.Equals("Even"))
                        serialPort1.Parity = System.IO.Ports.Parity.Even;
                    else if (comboBox4.Text.Equals("Mark"))
                        serialPort1.Parity = System.IO.Ports.Parity.Mark;
                    else if (comboBox4.Text.Equals("Space"))
                        serialPort1.Parity = System.IO.Ports.Parity.Space;

                    if (comboBox5.Text.Equals("1"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.One;
                    else if (comboBox5.Text.Equals("1.5"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
                    else if (comboBox5.Text.Equals("2"))
                        serialPort1.StopBits = System.IO.Ports.StopBits.Two;

                    serialPort1.Open();     //打開串口
                    button1.Text = "關閉串口";
                    button1.BackColor = Color.Firebrick;
         
                    this.Activate();
                }
            }
            catch (Exception ex)
            {
                //捕獲可能發生的異常並進行處理

                //捕獲到異常,建立一個新的對象,以前的不能夠再用
                serialPort1 = new System.IO.Ports.SerialPort();
                //刷新COM口選項
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //響鈴並顯示異常給用戶
                System.Media.SystemSounds.Beep.Play();
                button1.Text = "打開串口";
                button1.BackColor = Color.ForestGreen;
                MessageBox.Show(ex.Message);
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
                comboBox5.Enabled = true;
            }
        }

消息傳送

這個也沒有太多特別的,只要調用Write方法便可學習

private void SendBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Console.WriteLine(serialPort1.IsOpen);
                //首先判斷串口是否開啓
                if (serialPort1.IsOpen)
                {
                    //串口處於開啓狀態,將發送區文本發送
                    serialPort1.Write(SendTb.Text);
                    SendTb.Text = "";
                }
            }
            catch (Exception ex)
            {
                //捕獲到異常,建立一個新的對象,以前的不能夠再用
                serialPort1 = new System.IO.Ports.SerialPort();
                //刷新COM口選項
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
                //響鈴並顯示異常給用戶
                System.Media.SystemSounds.Beep.Play();
                button1.Text = "打開串口";
                button1.BackColor = Color.ForestGreen;
                MessageBox.Show(ex.Message);
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                comboBox3.Enabled = true;
                comboBox4.Enabled = true;
                comboBox5.Enabled = true;
            }
        }

以上的幾個基本功能其實只要調用方法再加上處理異常便可ui

接收消息

這個接收消息就很是靈活了,說簡單簡單,說難也有點難,若是要求不高,只是爲了展現出接收的消息,的確能夠有很簡單的方法this

這是最簡單的方法,只是單純的將緩存區獲得的字符拼接在一塊兒,可是若是傳進來的數據不僅一類,咱們須要將其中每一種分離出來,這種及時從緩存區取出來並拼接在一塊兒就不太適用了,由於從緩存區取出的字符不必定是完整的搜索引擎

String str = serialPort1.ReadExisting();

所以,我求助於搜索引擎,瞭解到要解決這個問題,咱們須要先將獲得的字符放在緩存區中,等緩存區積攢了必定的字符再進行讀取,每次提取必定的字符後,清空緩存區,將我拿到的這一串字符,轉換爲數組,我這個例子中有三個參數x y z,我就是將三個參數從下位機中按順序傳入,而後接收的時候以逗號做爲分隔符進行拆分(我在單片機上發送消息的時候就用逗號分隔參數了),那麼按順序咱們獲得的數據就是x1,x2,x3···那麼咱們只要記錄下如今處理的是哪一個參數就能夠按需處理了。
可是依然有不能解決的問題,就是若頻率太高,處理的速度就跟不上了,可是現實狀況中並非每幾毫米調用一次,因此我以爲這個問題也能夠忽略不計rest

private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                //由於要訪問UI資源,因此須要使用invoke方式同步ui
                this.Invoke((EventHandler)(delegate
                {
                  
                    int byteNumber = serialPort1.BytesToRead;

                    Thread.Sleep(20);


                    //延時等待數據接收完畢。
                    while ((byteNumber < serialPort1.BytesToRead) && (serialPort1.BytesToRead < 77))
                    {
                        byteNumber = serialPort1.BytesToRead;
                        Thread.Sleep(20);

                    }
                    int n = serialPort1.BytesToRead; //記錄下緩衝區的字節個數 

                    //Console.WriteLine("n" + n);
                    byte[] buf = new byte[n]; //聲明一個臨時數組存儲當前來的串口數據 
                    serialPort1.Read(buf, 0, n); //讀取緩衝數據到buf中,同時將這串數據從緩衝區移除 
                    string str = System.Text.Encoding.Default.GetString(buf);
                    string[] strArray = str.Split(',');
                    

                    int count = 0;
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        if(count == 0)
                        {
                            textBox1.Text = strArray[i];
                        }else if(count == 1)
                        {
                            textBox2.Text = strArray[i];
                        }else if(count == 2)
                        {
                            textBox3.Text = strArray[i];
                        }
                        count++;
                        if(count == 3)
                        {
                            count = 0;
                        }

                    }




                }
                   )
                );

            }
            catch (Exception ex)
            {
                //響鈴並顯示異常給用戶
                System.Media.SystemSounds.Beep.Play();
                MessageBox.Show(ex.Message);

            }
        }

那麼下一步是爲其添加上一個視頻面板以及遙控手柄,加油繼續學習

參考來源:http://www.javashuo.com/article/p-oqyrnrra-mm.html

相關文章
相關標籤/搜索