C# COM Port connet and sample code

前言

序列埠(Serial port),也稱序列埠或序列埠,序列通信埠,COM埠,簡稱串口。主要用於序列式逐資料傳輸。常見的有一般電腦應用的RS-232(使用 25 針或 9 針連接器)和工業電腦應用的半雙工RS-485全雙工RS-422
首先我們因為編寫一個UI介面要與STM32板子相互連接資料傳輸,第一步就是撰寫COM Port

Demo效果

前置作業

程式架構為:按下button,進行RS232連線,並在Listbox顯示可連線之COM Port與連線狀態。連線成功後,將MCU傳輸值顯示在Listbox上。

PS:這邊注意開啟的專案有2個選擇是.NET Framework才會在工具列裡出現SerialPort的選項

程式範例

1.首先宣告一個Serial變數

SerialPort serialPort1 = new SerialPort();

2.撰寫button點擊後動作

 private void button1_Click(object sender, EventArgs e)
        {
            System.String[] message = SerialPort.GetPortNames(); ;
            listBox1.Items.Add("正在尋找port");
            try
            {
                message = SerialPort.GetPortNames();
            }
            catch (Win32Exception ex)
            { Console.WriteLine(ex.Message); }
            listBox1.Items.Clear();
            listBox1.Items.Add("選擇port...");
            foreach (var item in message)
            { listBox1.Items.Add(System.String.Format("{0}", item)); }
        }

3.進行串列埠連線(因這邊有撰寫BaudRate可以透過外部文件改寫所以有一點點不同)

 private void OpenCom()
        {
            listBox1.Items.Add(Environment.NewLine);
            System.String PortNow = serialPort1.PortName;
            try
            {
                int B = 115200;
                if (textBox1.Text == null)
                {
                    B = Convert.ToInt32(textBox1.Text);
                }
                serialPort1.BaudRate = B;
                //資料位
                serialPort1.DataBits = 8;
                //serialPort1.PortName = comboBox1.Text;
                //兩個停止位
                // serialPort1.StopBits = System.IO.Ports.StopBits.One;
                serialPort1.Encoding = System.Text.Encoding.GetEncoding("GB2312");
                //無奇偶校驗位
                serialPort1.Parity = System.IO.Ports.Parity.None;
                serialPort1.ReadTimeout = 100;
                serialPort1.Open();
                listBox1.Items.Clear();
                listBox1.Items.Add(System.String.Format("{0}開啟成功", PortNow));
                serialPort1.DataReceived += serialPort1_DataReceived;
            }
            catch (System.Exception ex)
            {

                listBox1.Items.Add(ex.Message);
                serialPort1.Close();
            }
        
    }

4.撰寫關閉Com Port

        private void CloseCom()
        {
            serialPort1.Close();
            listBox1.Items.Add("關閉port...");
        }

5.撰寫連接觸發事件

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.String curItem = listBox1.SelectedItem.ToString();
            if(!serialPort1.IsOpen)
            {
                
                serialPort1.PortName = curItem;
                OpenCom();

            }
            else { CloseCom(); }
        }

7.串列埠接收資料事件

private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Thread.Sleep(50);  //(毫秒)等待一定時間,確保資料的完整性 int len        
    int len = serialPort1.BytesToRead;
    string receivedata = string.Empty;
    if (len != 0)
    {
        byte[] buff = new byte[len];
        serialPort1.Read(buff, 0, len);
        receivedata = Encoding.Default.GetString(buff);
                
    }
    richTextBox1.AppendText(receivedata + "\r\n");
}

額外功能

串列埠傳送資料

serialPort1.Write(textBox1.Text);

斷開串列埠

serialPort1.Dispose();

得到可用串列埠號

String[] portnames = SerialPort.GetPortNames();
foreach (var item in portnames)
{
    comboBox1.Items.Add(item);
}

PS:這邊注意serialPort1.Dispose();與serialPort1.Close(); 2者不同處是Dispose()是釋放全部內存,Close()是完全斷開並釋放內存

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart